file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
pragma experimental "v0.5.0"; //////////////////// // HOURLY PAY // // CONTRACT // // v 0.2.1 // //////////////////// // The Hourly Pay Contract allows you to track your time and get paid a hourly wage for tracked time. // // HOW IT WORKS: // // 1. Client creates the contract, making himself the owner of the contract. // // 2. Client can fund the contract with ETH by simply sending money to the contract (via payable fallback function). // // 3. Before hiring someone, client can change additional parameters, such as: // // - setContractDurationInDays(days) - The duration of the contract (default is 365 days). // // - setDailyHourLimit(hours) - How much hours the Employee can work per day (default is 8 hours). // // - setPaydayFrequencyInDays(days) - How often the Employee can withdraw the earnings (default is every 3 days). // // - setBeginTimeTS(utcTimestamp) - Work on contract can be started after this timestamp (default is contract creation time). // Also defines the start of Day and Week for accounting and daily limits. // Day transition time should be convenient for the employee (like 4am), // so that work doesn't cross between days, // The excess won't be transferred to the next day. // // 4. Client hires the Employee by invoking hire(addressOfEmployee, ratePerHourInWei) // This starts the project and puts the contract in a workable state. // Before hiring, contract should be loaded with enough ETH to provide at least one day of work at specified ratePerHourInWei // // 5. To start work and earn ETH the Employee should: // // invoke startWork() when he starts working to run the timer. // // invoke stopWork() when he finishes working to stop the timer. // // After the timer is stopped - the ETH earnings are calculated and recorded on Employee's internal balance. // If the stopWork() is invoked after more hours had passed than dailyLimit - the excess is ignored // and only the dailyLimit is added to the internal balance. // // 6. Employee can withdraw earnings from internal balance after paydayFrequencyInDays days have passed after BeginTimeTS: // by invoking withdraw() // // After each withdrawal the paydayFrequencyInDays is reset and starts counting itself from the TS of the first startWork() after withdrawal. // // This delay is implemented as a safety mechanism, so the Client can have time to check the work and // cancel the earnings if something goes wrong. // That way only money earned during the last paydayFrequencyInDays is at risk. // // 7. Client can fire() the Employee after his services are no longer needed. // That would stop any ongoing work by terminating the timer and won't allow to start the work again. // // 8. If anything in the relationship or hour counting goes wrong, there are safety functions: // - refundAll() - terminates all unwithdrawn earnings. // - refund(amount) - terminates the (amount) of unwithdrawn earnings. // Can be only called if not working. // Both of these can be called by Client or Employee. // * TODO: Still need to think if allowing Client to do that won't hurt the Employee. // * TODO: SecondsWorkedToday don't reset after refund, so dailyLimit still affects // * TODO: Think of a better name. ClearEarnings? // // 9. Client can withdraw any excess ETH from the contract via: // - clientWithdrawAll() - withdraws all funds minus locked in earnings. // - clientWithdraw(amount) - withdraws (amount), not locked in earnings. // Can be invoked only if Employee isn't hired or has been fired. // // 10. Client and Contract Ownership can be made "Public"/"None" by calling: // - releaseOwnership() // It simply sets the Owner (Client) to 0x0, so no one is in control of the contract anymore. // That way the contract can be used on projects as Hourly-Wage Donations. // /////////////////////////////////////////////////////////////////////////////////////////////////// contract HourlyPay { //////////////////////////////// // Addresses address public owner; // Client and owner address address public employeeAddress = 0x0; // Employee address ///////////////////////////////// // Contract business properties uint public beginTimeTS; // When the contract work can be started. Also TS of day transition. uint public ratePerHourInWei; // Employee rate in wei uint public earnings = 0; // Earnings of employee bool public hired = false; // If the employee is hired and approved to perform work bool public working = false; // Is employee currently working with timer on? uint public startedWorkTS; // Timestamp of when the timer started counting time uint public workedTodayInSeconds = 0; // How many seconds worked today uint public currentDayTS; uint public lastPaydayTS; string public contractName = "Hourly Pay Contract"; //////////////////////////////// // Contract Limits and maximums uint16 public contractDurationInDays = 365; // Overall contract duration in days, default is 365 and it's also maximum for safety reasons uint8 public dailyHourLimit = 8; // Limits the hours per day, max 24 hours uint8 public paydayFrequencyInDays = 3; // How often can Withdraw be called, default is every 3 days uint8 constant hoursInWeek = 168; uint8 constant maxDaysInFrequency = 30; // every 30 days is a wise maximum //////////////// // Constructor constructor() public { owner = msg.sender; beginTimeTS = now; currentDayTS = beginTimeTS; lastPaydayTS = beginTimeTS; } ////////////// // Modifiers modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyEmployee { require(msg.sender == employeeAddress); _; } modifier onlyOwnerOrEmployee { require((msg.sender == employeeAddress) || (msg.sender == owner)); _; } modifier beforeHire { require(employeeAddress == 0x0); // Contract can hire someone only once require(hired == false); // Shouldn't be already hired _; } /////////// // Events event GotFunds(address sender, uint amount); event ContractDurationInDaysChanged(uint16 contractDurationInDays); event DailyHourLimitChanged(uint8 dailyHourLimit); event PaydayFrequencyInDaysChanged(uint32 paydayFrequencyInDays); event BeginTimeTSChanged(uint beginTimeTS); event Hired(address employeeAddress, uint ratePerHourInWei, uint hiredTS); event NewDay(uint currentDayTS, uint16 contractDaysLeft); event StartedWork(uint startedWorkTS, uint workedTodayInSeconds, string comment); event StoppedWork(uint stoppedWorkTS, uint workedInSeconds, uint earned); event Withdrawal(uint amount, address employeeAddress, uint withdrawalTS); event Fired(address employeeAddress, uint firedTS); event Refunded(uint amount, address whoInitiatedRefund, uint refundTS); event ClientWithdrawal(uint amount, uint clientWithdrawalTS); event ContractNameChanged(string contractName); //////////////////////////////////////////////// // Fallback function to fund contract with ETH function () external payable { emit GotFunds(msg.sender, msg.value); } /////////////////////////// // Main Setters function setContractName(string newContractName) external onlyOwner beforeHire { contractName = newContractName; emit ContractNameChanged(contractName); } function setContractDurationInDays(uint16 newContractDurationInDays) external onlyOwner beforeHire { require(newContractDurationInDays <= 365); contractDurationInDays = newContractDurationInDays; emit ContractDurationInDaysChanged(contractDurationInDays); } function setDailyHourLimit(uint8 newDailyHourLimit) external onlyOwner beforeHire { require(newDailyHourLimit <= 24); dailyHourLimit = newDailyHourLimit; emit DailyHourLimitChanged(dailyHourLimit); } function setPaydayFrequencyInDays(uint8 newPaydayFrequencyInDays) external onlyOwner beforeHire { require(newPaydayFrequencyInDays < maxDaysInFrequency); paydayFrequencyInDays = newPaydayFrequencyInDays; emit PaydayFrequencyInDaysChanged(paydayFrequencyInDays); } function setBeginTimeTS(uint newBeginTimeTS) external onlyOwner beforeHire { beginTimeTS = newBeginTimeTS; currentDayTS = beginTimeTS; lastPaydayTS = beginTimeTS; emit BeginTimeTSChanged(beginTimeTS); } /////////////////// // Helper getters function getWorkSecondsInProgress() public view returns(uint) { if (!working) return 0; return now - startedWorkTS; } function isOvertime() external view returns(bool) { if (workedTodayInSeconds + getWorkSecondsInProgress() > dailyHourLimit * 1 hours) return true; return false; } function hasEnoughFundsToStart() public view returns(bool) { return ((address(this).balance > earnings) && (address(this).balance - earnings >= ratePerHourInWei * (dailyHourLimit * 1 hours - (isNewDay() ? 0 : workedTodayInSeconds)) / 1 hours)); } function isNewDay() public view returns(bool) { return (now - currentDayTS > 1 days); } function canStartWork() public view returns(bool) { return (hired && !working && (now > beginTimeTS) && (now < beginTimeTS + (contractDurationInDays * 1 days)) && hasEnoughFundsToStart() && ((workedTodayInSeconds < dailyHourLimit * 1 hours) || isNewDay())); } function canStopWork() external view returns(bool) { return (working && hired && (now > startedWorkTS)); } function currentTime() external view returns(uint) { return now; } function getBalance() external view returns(uint) { return address(this).balance; } //////////////////////////// // Main workflow functions function releaseOwnership() external onlyOwner { owner = 0x0; } function hire(address newEmployeeAddress, uint newRatePerHourInWei) external onlyOwner beforeHire { require(newEmployeeAddress != 0x0); // Protection from burning the ETH // Contract should be loaded with ETH for a minimum one day balance to perform Hire: // require(address(this).balance >= newRatePerHourInWei * dailyHourLimit); employeeAddress = newEmployeeAddress; ratePerHourInWei = newRatePerHourInWei; hired = true; emit Hired(employeeAddress, ratePerHourInWei, now); } function startWork(string comment) external onlyEmployee { require(hired == true); require(working == false); require(now > beginTimeTS); // can start working only after contract beginTimeTS require(now < beginTimeTS + (contractDurationInDays * 1 days)); // can't start after contractDurationInDays has passed since beginTimeTS checkForNewDay(); require(workedTodayInSeconds < dailyHourLimit * 1 hours); // can't start if already approached dailyHourLimit require(address(this).balance > earnings); // balance must be greater than earnings // balance minus earnings must be sufficient for at least 1 day of work minus workedTodayInSeconds: // require(address(this).balance - earnings >= ratePerHourInWei * (dailyHourLimit * 1 hours - workedTodayInSeconds) / 1 hours); if (earnings == 0) lastPaydayTS = now; // reset the payday timer TS if this is the first time work starts after last payday startedWorkTS = now; working = true; emit StartedWork(startedWorkTS, workedTodayInSeconds, comment); } function checkForNewDay() internal { if (now - currentDayTS > 1 days) { // new day while (currentDayTS < now) { currentDayTS += 1 days; } currentDayTS -= 1 days; workedTodayInSeconds = 0; emit NewDay(currentDayTS, uint16 ((beginTimeTS + (contractDurationInDays * 1 days) - currentDayTS) / 1 days)); } } function stopWork() external onlyEmployee { stopWorkInternal(); } function stopWorkInternal() internal { require(hired == true); require(working == true); require(now > startedWorkTS); // just a temporary overflow check, in case of miners manipulate time uint newWorkedTodayInSeconds = workedTodayInSeconds + (now - startedWorkTS); if (newWorkedTodayInSeconds > dailyHourLimit * 1 hours) { // check for overflow newWorkedTodayInSeconds = dailyHourLimit * 1 hours; // and assign max dailyHourLimit if there is an overflow } uint earned = (newWorkedTodayInSeconds - workedTodayInSeconds) * ratePerHourInWei / 1 hours; uint newEarnings = earnings + earned; // add new earned ETH to earnings if (newEarnings > address(this).balance) { earned = address(this).balance - earnings; earnings = address(this).balance; } else { earnings = newEarnings; } emit StoppedWork(now, newWorkedTodayInSeconds - workedTodayInSeconds, earned); workedTodayInSeconds = newWorkedTodayInSeconds; // updated todays works in seconds working = false; checkForNewDay(); } function withdraw() external onlyEmployee { require(working == false); require(earnings > 0); require(earnings <= address(this).balance); require(now - lastPaydayTS > paydayFrequencyInDays * 1 days); // check if payday frequency days passed after last withdrawal lastPaydayTS = now; uint amountToWithdraw = earnings; earnings = 0; employeeAddress.transfer(amountToWithdraw); emit Withdrawal(amountToWithdraw, employeeAddress, now); } function withdrawAfterEnd() external onlyEmployee { require(owner == 0x0); // only if there's no owner require(now > beginTimeTS + (contractDurationInDays * 1 days)); // only after contract end require(address(this).balance > 0); // only if there's balance employeeAddress.transfer(address(this).balance); emit Withdrawal(address(this).balance, employeeAddress, now); } function fire() external onlyOwner { if (working) stopWorkInternal(); // cease all motor functions if working hired = false; // fire emit Fired(employeeAddress, now); } function refundAll() external onlyOwnerOrEmployee { // terminates all unwithdrawn earnings. require(working == false); require(earnings > 0); uint amount = earnings; earnings = 0; emit Refunded(amount, msg.sender, now); } function refund(uint amount) external onlyOwnerOrEmployee { // terminates the (amount) of unwithdrawn earnings. require(working == false); require(amount < earnings); earnings -= amount; emit Refunded(amount, msg.sender, now); } function clientWithdrawAll() external onlyOwner { // withdraws all funds minus locked in earnings. require(hired == false); require(address(this).balance > earnings); uint amount = address(this).balance - earnings; owner.transfer(amount); emit ClientWithdrawal(amount, now); } function clientWithdraw(uint amount) external onlyOwner { // withdraws (amount), if not locked in earnings. require(hired == false); require(address(this).balance > earnings); require(amount < address(this).balance); require(address(this).balance - amount > earnings); owner.transfer(amount); emit ClientWithdrawal(amount, now); } }
only after contract end
require(now > beginTimeTS + (contractDurationInDays * 1 days));
916,106
[ 1, 3700, 1839, 6835, 679, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 2583, 12, 3338, 405, 2376, 950, 8047, 397, 261, 16351, 5326, 382, 9384, 380, 404, 4681, 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 ]
pragma solidity ^0.4.25; /*** @title SafeMath*/ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /*** @title ERC20 interface */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function allowance(address _owner, address _spender) public view returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /*** @title ERC223 interface */ contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } contract ERC223 { function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public returns(bool); function transfer(address to, uint value, bytes data) public returns(bool); event Transfer(address indexed from, address indexed to, uint value); //ERC 20 style //event Transfer(address indexed from, address indexed to, uint value, bytes data); } /*** @title ERC223 token */ contract ERC223Token is ERC223{ using SafeMath for uint; mapping(address => uint256) balances; function transfer(address _to, uint _value) public returns(bool){ uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } require(_value > 0); require(balances[msg.sender] >= _value); require(balances[_to]+_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); return false; } emit Transfer(msg.sender, _to, _value); return true; } function transfer(address _to, uint _value, bytes _data) public returns(bool){ // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } require(_value > 0); require(balances[msg.sender] >= _value); require(balances[_to]+_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); return false; } emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } ////////////////////////////////////////////////////////////////////////// //////////////////////// [Ding token] MAIN //////////////////////// ////////////////////////////////////////////////////////////////////////// /*** @title Owned */ contract Owned { address public owner; constructor() public { owner = msg.sender; //owner = 0x43Fb2e04aC5B382Fc6ff29Ac34D3Ca221cEE402E; } modifier onlyOwner { require(msg.sender == owner); _; } } /*** @title Ding Token */ contract DING is ERC223Token, Owned{ string public constant name = "Ding Ding Token"; string public constant symbol = "DING"; uint8 public constant decimals = 18; uint256 public tokenRemained = 2 * (10 ** 9) * (10 ** 18); // 2 billion DING, decimals set to 18 uint256 public totalSupply = 2 * (10 ** 9) * (10 ** 18); bool public pause=false; mapping(address => bool) lockAddresses; // constructor function DING(){ //allocate to ______ balances[0xd8686d2aB1a65149FDd4ee36c60d161c274C41e0]= totalSupply; emit Transfer(0x0,0xd8686d2aB1a65149FDd4ee36c60d161c274C41e0,totalSupply); } // change the contract owner event ChangeOwner(address indexed _from,address indexed _to); function changeOwner(address _new) public onlyOwner{ emit ChangeOwner(owner,_new); owner=_new; } // pause all the transfer on the contract event PauseContract(); function pauseContract() public onlyOwner{ pause = true; emit PauseContract(); } event ResumeContract(); function resumeContract() public onlyOwner{ pause = false; emit ResumeContract(); } function is_contract_paused() public view returns(bool){ return pause; } // lock one's wallet event Lock(address _addr); function lock(address _addr) public onlyOwner{ lockAddresses[_addr] = true; emit Lock(_addr); } event Unlock(address _addr); function unlock(address _addr) public onlyOwner{ lockAddresses[_addr] = false; emit Unlock(_addr); } function am_I_locked(address _addr) public view returns(bool){ return lockAddresses[_addr]; } // eth function() payable { } function getETH(uint256 _amount) public onlyOwner{ msg.sender.transfer(_amount); } ///////////////////////////////////////////////////////////////////// ///////////////// ERC223 Standard functions ///////////////////////// ///////////////////////////////////////////////////////////////////// modifier transferable(address _addr) { require(!pause); require(!lockAddresses[_addr]); _; } function transfer(address _to, uint _value, bytes _data) public transferable(msg.sender) returns (bool) { return super.transfer(_to, _value, _data); } function transfer(address _to, uint _value) public transferable(msg.sender) returns (bool) { return super.transfer(_to, _value); } ///////////////////////////////////////////////////////////////////// /////////////////// Rescue functions ////////////////////////////// ///////////////////////////////////////////////////////////////////// function transferAnyERC20Token(address _tokenAddress, uint256 _value) public onlyOwner returns (bool) { return ERC20(_tokenAddress).transfer(owner, _value); } }
** @title SafeMath*/
library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { uint c = a / b; return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } function assert(bool assertion) internal { if (!assertion) { throw; } } }
5,494,816
[ 1, 9890, 10477, 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, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 202, 915, 14064, 12, 11890, 279, 16, 2254, 324, 13, 2713, 1135, 261, 11890, 13, 288, 203, 202, 202, 11890, 276, 273, 279, 380, 324, 31, 203, 202, 202, 11231, 12, 69, 422, 374, 747, 276, 342, 279, 422, 324, 1769, 203, 202, 202, 2463, 276, 31, 203, 202, 97, 203, 202, 915, 3739, 12, 11890, 279, 16, 2254, 324, 13, 2713, 1135, 261, 11890, 13, 288, 203, 202, 202, 11890, 276, 273, 279, 342, 324, 31, 203, 202, 202, 2463, 276, 31, 203, 202, 97, 203, 202, 915, 720, 12, 11890, 279, 16, 2254, 324, 13, 2713, 1135, 261, 11890, 13, 288, 203, 202, 202, 11231, 12, 70, 1648, 279, 1769, 203, 202, 202, 2463, 279, 300, 324, 31, 203, 202, 97, 203, 202, 915, 527, 12, 11890, 279, 16, 2254, 324, 13, 2713, 1135, 261, 11890, 13, 288, 203, 202, 202, 11890, 276, 273, 279, 397, 324, 31, 203, 202, 202, 11231, 12, 71, 1545, 279, 1769, 203, 202, 202, 2463, 276, 31, 203, 202, 97, 203, 202, 915, 943, 1105, 12, 11890, 1105, 279, 16, 2254, 1105, 324, 13, 2713, 5381, 1135, 261, 11890, 1105, 13, 288, 203, 202, 202, 2463, 279, 1545, 324, 692, 279, 294, 324, 31, 203, 202, 97, 203, 202, 915, 1131, 1105, 12, 11890, 1105, 279, 16, 2254, 1105, 324, 13, 2713, 5381, 1135, 261, 11890, 1105, 13, 288, 203, 202, 202, 2463, 279, 411, 324, 692, 279, 294, 324, 31, 203, 202, 97, 203, 202, 915, 943, 5034, 12, 11890, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; contract Owned { address public owner; address public proposedOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() virtual { require(msg.sender == owner); _; } /** * @dev propeses a new owner * Can only be called by the current owner. */ function proposeOwner(address payable _newOwner) external onlyOwner { proposedOwner = _newOwner; } /** * @dev claims ownership of the contract * Can only be called by the new proposed owner. */ function claimOwnership() external { require(msg.sender == proposedOwner); emit OwnershipTransferred(owner, proposedOwner); owner = proposedOwner; } } // 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity 0.8.4; contract MishuInuFinance is ERC20, Owned { uint256 public minSupply; address public beneficiary; bool public feesEnabled; mapping(address => bool) public isExcludedFromFee; event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount); event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary); event FeesEnabledUpdated(bool enabled); event ExcludedFromFeeUpdated(address account, bool excluded); constructor() ERC20("Mishu Inu Finance", "Mishu") { minSupply = 100000000 ether; uint256 totalSupply = 1000000000000000 ether; feesEnabled = false; _mint(_msgSender(), totalSupply); isExcludedFromFee[msg.sender] = true; isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true; beneficiary = msg.sender; } /** * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary * @dev after a certain threshold, try to swap collected fees automatically * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed */ function _transfer( address sender, address recipient, uint256 amount ) internal override { require( recipient != address(this), "Cannot send tokens to token contract" ); if ( !feesEnabled || isExcludedFromFee[sender] || isExcludedFromFee[recipient] ) { ERC20._transfer(sender, recipient, amount); return; } // burn tokens if min supply not reached yet uint256 burnedFee = calculateFee(amount, 25); if (totalSupply() - burnedFee >= minSupply) { _burn(sender, burnedFee); } else { burnedFee = 0; } uint256 transferFee = calculateFee(amount, 200); ERC20._transfer(sender, beneficiary, transferFee); ERC20._transfer(sender, recipient, amount - transferFee - burnedFee); } function calculateFee(uint256 _amount, uint256 _fee) public pure returns (uint256) { return (_amount * _fee) / 10000; } /** * @notice allows to burn tokens from own balance * @dev only allows burning tokens until minimum supply is reached * @param value amount of tokens to burn */ function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); } /** * @notice sets minimum supply of the token * @dev only callable by owner * @param _newMinSupply new minimum supply */ function setMinSupply(uint256 _newMinSupply) public onlyOwner { emit MinSupplyUpdated(minSupply, _newMinSupply); minSupply = _newMinSupply; } /** * @notice sets recipient of transfer fee * @dev only callable by owner * @param _newBeneficiary new beneficiary */ function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; } /** * @notice sets whether account collects fees on token transfer * @dev only callable by owner * @param _enabled bool whether fees are enabled */ function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; } /** * @notice adds or removes an account that is exempt from fee collection * @dev only callable by owner * @param _account account to modify * @param _excluded new value */ function setExcludeFromFee(address _account, bool _excluded) public onlyOwner { isExcludedFromFee[_account] = _excluded; emit ExcludedFromFeeUpdated(_account, _excluded); } }
* @dev Throws if called by any account other than the owner./
modifier onlyOwner() virtual { require(msg.sender == owner); _; }
13,181
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5541, 1435, 5024, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 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 ]
./full_match/1/0x2B6d357b0585Be3DBc448366A23486437ba2015C/sources/lib/solady/src/utils/Multicallable.sol
@dev Apply `DELEGATECALL` with the current contract to each calldata in `data`, and store the `abi.encode` formatted results of each `DELEGATECALL` into `results`. If any of the `DELEGATECALL`s reverts, the entire transaction is reverted, and the error is bubbled up. Early return if no data. `shl` 5 is equivalent to multiplying by 0x20. Copy the offsets from calldata into memory. Pointer to the top of the memory (i.e. start of the free memory). The offset of the current bytes in the calldata. Copy the current bytes from calldata to the memory. Bubble up the revert if the delegatecall reverts.
function multicall(bytes[] calldata data) external payable virtual returns (bytes[] memory) { assembly { mstore(0x00, 0x20) let results := 0x40 let end := shl(5, data.length) calldatacopy(0x40, data.offset, end) let resultsOffset := end let o := add(data.offset, mload(results)) let memPtr := add(resultsOffset, 0x40) calldatacopy( memPtr, ) if iszero(delegatecall(gas(), address(), memPtr, calldataload(o), 0x00, 0x00)) { returndatacopy(0x00, 0x00, returndatasize()) revert(0x00, returndatasize()) } results := add(results, 0x20) returndatacopy(add(memPtr, 0x20), 0x00, returndatasize()) and(add(add(resultsOffset, returndatasize()), 0x3f), 0xffffffffffffffe0) } return(0x00, add(resultsOffset, 0x40)) }
4,914,141
[ 1, 7001, 1375, 1639, 19384, 1777, 13730, 68, 598, 326, 783, 6835, 358, 1517, 745, 892, 316, 1375, 892, 9191, 471, 1707, 326, 1375, 21457, 18, 3015, 68, 4955, 1686, 434, 1517, 1375, 1639, 19384, 1777, 13730, 68, 1368, 1375, 4717, 8338, 971, 1281, 434, 326, 1375, 1639, 19384, 1777, 13730, 68, 87, 15226, 87, 16, 326, 7278, 2492, 353, 15226, 329, 16, 471, 326, 555, 353, 324, 22298, 1259, 731, 18, 512, 20279, 327, 309, 1158, 501, 18, 1375, 674, 80, 68, 1381, 353, 7680, 358, 10194, 310, 635, 374, 92, 3462, 18, 5631, 326, 8738, 628, 745, 892, 1368, 3778, 18, 7107, 358, 326, 1760, 434, 326, 3778, 261, 77, 18, 73, 18, 787, 434, 326, 4843, 3778, 2934, 1021, 1384, 434, 326, 783, 1731, 316, 326, 745, 892, 18, 5631, 326, 783, 1731, 628, 745, 892, 358, 326, 3778, 18, 605, 14787, 731, 326, 15226, 309, 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, 1778, 335, 454, 12, 3890, 8526, 745, 892, 501, 13, 3903, 8843, 429, 5024, 1135, 261, 3890, 8526, 3778, 13, 288, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 20, 92, 713, 16, 374, 92, 3462, 13, 203, 203, 5411, 2231, 1686, 519, 374, 92, 7132, 203, 5411, 2231, 679, 519, 699, 80, 12, 25, 16, 501, 18, 2469, 13, 203, 5411, 745, 892, 3530, 12, 20, 92, 7132, 16, 501, 18, 3348, 16, 679, 13, 203, 5411, 2231, 1686, 2335, 519, 679, 203, 203, 7734, 2231, 320, 519, 527, 12, 892, 18, 3348, 16, 312, 945, 12, 4717, 3719, 203, 7734, 2231, 1663, 5263, 519, 527, 12, 4717, 2335, 16, 374, 92, 7132, 13, 203, 7734, 745, 892, 3530, 12, 203, 10792, 1663, 5263, 16, 203, 7734, 262, 203, 7734, 309, 353, 7124, 12, 22216, 1991, 12, 31604, 9334, 1758, 9334, 1663, 5263, 16, 745, 72, 3145, 6189, 12, 83, 3631, 374, 92, 713, 16, 374, 92, 713, 3719, 288, 203, 10792, 327, 892, 3530, 12, 20, 92, 713, 16, 374, 92, 713, 16, 327, 13178, 554, 10756, 203, 10792, 15226, 12, 20, 92, 713, 16, 327, 13178, 554, 10756, 203, 7734, 289, 203, 7734, 1686, 519, 527, 12, 4717, 16, 374, 92, 3462, 13, 203, 7734, 327, 892, 3530, 12, 1289, 12, 3917, 5263, 16, 374, 92, 3462, 3631, 374, 92, 713, 16, 327, 13178, 554, 10756, 203, 10792, 471, 12, 1289, 12, 1289, 12, 4717, 2335, 16, 327, 13178, 554, 1435, 3631, 374, 92, 23, 74, 3631, 374, 2 ]
./partial_match/1/0x9d08CCeD85A68Bf8A19374ED4B5753aE3Be9F74f/sources/contracts/protocol/integration/lib/AaveV3.sol
* Get borrow calldata from SetToken Allows users to borrow a specific `_amountNotional` of the reserve underlying `_asset`, provided that the borrower already supplied enough collateral, or he was given enough allowance by a credit delegator on the corresponding debt token (StableDebtToken or VariableDebtToken) @param _pool Address of the AaveV3 Pool contract @param _asset The address of the underlying asset to borrow @param _amountNotional The amount to be borrowed @param _interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable @param _referralCode Code used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-man @param _onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself calling the function if he wants to borrow against his own collateral, or the address of the credit delegator if he has been given credit delegation allowance @return address Target contract address @return uint256 Call value @return bytes Borrow calldata/
function getBorrowCalldata( IPool _pool, address _asset, uint256 _amountNotional, uint256 _interestRateMode, uint16 _referralCode, address _onBehalfOf ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "borrow(address,uint256,uint256,uint16,address)", _asset, _amountNotional, _interestRateMode, _referralCode, _onBehalfOf ); return (address(_pool), 0, callData); }
15,718,217
[ 1, 967, 29759, 745, 892, 628, 1000, 1345, 25619, 3677, 358, 29759, 279, 2923, 1375, 67, 8949, 1248, 285, 287, 68, 434, 326, 20501, 6808, 1375, 67, 9406, 9191, 2112, 716, 326, 29759, 264, 1818, 4580, 7304, 4508, 2045, 287, 16, 578, 3904, 1703, 864, 7304, 1699, 1359, 635, 279, 12896, 11158, 639, 603, 326, 4656, 18202, 88, 1147, 261, 30915, 758, 23602, 1345, 578, 7110, 758, 23602, 1345, 13, 225, 389, 6011, 1171, 5267, 434, 326, 432, 836, 58, 23, 8828, 6835, 225, 389, 9406, 7734, 1021, 1758, 434, 326, 6808, 3310, 358, 29759, 225, 389, 8949, 1248, 285, 287, 4202, 1021, 3844, 358, 506, 29759, 329, 225, 389, 2761, 395, 4727, 2309, 377, 1021, 16513, 4993, 1965, 622, 1492, 326, 729, 14805, 358, 29759, 30, 404, 364, 934, 429, 16, 576, 364, 7110, 225, 389, 1734, 370, 23093, 540, 3356, 1399, 358, 1744, 326, 11301, 639, 4026, 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, 2882, 15318, 1477, 892, 12, 203, 3639, 467, 2864, 389, 6011, 16, 203, 3639, 1758, 389, 9406, 16, 7010, 3639, 2254, 5034, 389, 8949, 1248, 285, 287, 16, 203, 3639, 2254, 5034, 389, 2761, 395, 4727, 2309, 16, 203, 3639, 2254, 2313, 389, 1734, 370, 23093, 16, 203, 3639, 1758, 389, 265, 1919, 20222, 951, 203, 565, 262, 203, 3639, 1071, 203, 3639, 16618, 203, 3639, 1135, 261, 2867, 16, 2254, 5034, 16, 1731, 3778, 13, 203, 565, 288, 203, 3639, 1731, 3778, 745, 751, 273, 24126, 18, 3015, 1190, 5374, 12, 203, 5411, 315, 70, 15318, 12, 2867, 16, 11890, 5034, 16, 11890, 5034, 16, 11890, 2313, 16, 2867, 2225, 16, 7010, 5411, 389, 9406, 16, 7010, 5411, 389, 8949, 1248, 285, 287, 16, 7010, 5411, 389, 2761, 395, 4727, 2309, 16, 203, 5411, 389, 1734, 370, 23093, 16, 203, 5411, 389, 265, 1919, 20222, 951, 203, 3639, 11272, 203, 540, 203, 3639, 327, 261, 2867, 24899, 6011, 3631, 374, 16, 745, 751, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 <= 0.7.5; import "./Collection.sol"; /** * @author Bruno C. P. Arruda * @title SmartDCPABE Utility Contract * @notice This contract acts as a Library, providing common, utility functions */ contract SmartDCPABEUtility is Collection { /** * @notice creates the contract with unset dependencies * @param root the address of the Root contract */ constructor(address root) Collection(root) {} /** * @inheritdoc Collection */ function setContractDependencies(ContractType contractType, address addr) public view override onlyOwner {} /** * @notice convert a string to a single word of 32 bytes. * Text must be at most 32 bytes of length * @param source the string to convert * @return result a bytes32 representation of the string */ function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); assert(tempEmptyStringTest.length <= 32); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 0x20)) } } /** * @notice convert a word of 32 bytes into a string. * @param source the bytes32 value to convert * @return value a string representation of the bytes32 array */ function bytes32ToString(bytes32 source) public pure returns (string memory value) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(source) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } value = string(bytesStringTrimmed); } /** * @notice removes trailing 0x00 in a bytes31 source and outputs the result as bytes * @param source a bytes31 value * @param size the offset of the data within the bytes31 value * @return output the result of the conversion */ function trimBytes31(bytes31 source, uint8 size) public pure returns (bytes memory output) { output = new bytes(size); bytes32 source32 = bytes32(source); for (uint j = 0; j < size; j++) { byte char = byte(bytes32(uint(source32) * 2 ** (8 * j))); output[j] = char; } return output; } }
* @author Bruno C. P. Arruda @title SmartDCPABE Utility Contract @notice This contract acts as a Library, providing common, utility functions/
contract SmartDCPABEUtility is Collection { pragma solidity ^0.7.0 <= 0.7.5; constructor(address root) Collection(root) {} function setContractDependencies(ContractType contractType, address addr) public view override onlyOwner {} function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); assert(tempEmptyStringTest.length <= 32); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 0x20)) } } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); assert(tempEmptyStringTest.length <= 32); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 0x20)) } } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); assert(tempEmptyStringTest.length <= 32); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 0x20)) } } function bytes32ToString(bytes32 source) public pure returns (string memory value) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(source) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } value = string(bytesStringTrimmed); } function bytes32ToString(bytes32 source) public pure returns (string memory value) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(source) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } value = string(bytesStringTrimmed); } function bytes32ToString(bytes32 source) public pure returns (string memory value) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(source) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } value = string(bytesStringTrimmed); } function bytes32ToString(bytes32 source) public pure returns (string memory value) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(source) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } value = string(bytesStringTrimmed); } function trimBytes31(bytes31 source, uint8 size) public pure returns (bytes memory output) { output = new bytes(size); bytes32 source32 = bytes32(source); for (uint j = 0; j < size; j++) { byte char = byte(bytes32(uint(source32) * 2 ** (8 * j))); output[j] = char; } return output; } function trimBytes31(bytes31 source, uint8 size) public pure returns (bytes memory output) { output = new bytes(size); bytes32 source32 = bytes32(source); for (uint j = 0; j < size; j++) { byte char = byte(bytes32(uint(source32) * 2 ** (8 * j))); output[j] = char; } return output; } }
12,915,510
[ 1, 38, 2681, 83, 385, 18, 453, 18, 10371, 13177, 225, 19656, 40, 4258, 2090, 41, 13134, 13456, 225, 1220, 6835, 22668, 487, 279, 18694, 16, 17721, 2975, 16, 12788, 4186, 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, 16351, 19656, 40, 4258, 2090, 41, 6497, 353, 2200, 288, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 1648, 374, 18, 27, 18, 25, 31, 203, 565, 3885, 12, 2867, 1365, 13, 2200, 12, 3085, 13, 2618, 203, 565, 445, 444, 8924, 8053, 12, 8924, 559, 6835, 559, 16, 1758, 3091, 13, 1071, 1476, 3849, 1338, 5541, 2618, 203, 565, 445, 14134, 2160, 1578, 12, 1080, 3778, 1084, 13, 1071, 16618, 1135, 261, 3890, 1578, 563, 13, 288, 203, 3639, 1731, 3778, 1906, 1921, 780, 4709, 273, 1731, 12, 3168, 1769, 203, 3639, 1815, 12, 5814, 1921, 780, 4709, 18, 2469, 1648, 3847, 1769, 203, 3639, 309, 261, 5814, 1921, 780, 4709, 18, 2469, 422, 374, 13, 288, 203, 5411, 327, 374, 92, 20, 31, 203, 3639, 289, 203, 3639, 19931, 288, 203, 5411, 563, 519, 312, 945, 12, 1289, 12, 3168, 16, 374, 92, 3462, 3719, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 14134, 2160, 1578, 12, 1080, 3778, 1084, 13, 1071, 16618, 1135, 261, 3890, 1578, 563, 13, 288, 203, 3639, 1731, 3778, 1906, 1921, 780, 4709, 273, 1731, 12, 3168, 1769, 203, 3639, 1815, 12, 5814, 1921, 780, 4709, 18, 2469, 1648, 3847, 1769, 203, 3639, 309, 261, 5814, 1921, 780, 4709, 18, 2469, 422, 374, 13, 288, 203, 5411, 327, 374, 92, 20, 31, 203, 3639, 289, 203, 3639, 19931, 288, 203, 5411, 563, 519, 312, 945, 12, 1289, 12, 3168, 16, 374, 92, 3462, 3719, 203, 3639, 289, 203, 565, 2 ]
./full_match/1/0xd6E5CE9EBd9e7340B3420E1584479208fF1B90f8/sources/contracts/FFF-GasVesting.sol
* @title TokenVesting/ start time of the vesting period cliff period in seconds duration of the vesting period in seconds duration of a slice period for the vesting in seconds whether or not the vesting is revocable
contract TokenVesting is Ownable, ReentrancyGuard{ using SafeMath for uint256; using SafeERC20 for IERC20; uint256 start = 1645049065; uint256 cliff = 1645049065; uint256 duration = 5184000; uint256 slicePeriodSeconds = 60; bool revocable = true; struct VestingSchedule{ bool initialized; address beneficiary; uint256 amountTotal; uint256 released; bool revoked; } bytes32[] private vestingSchedulesIds; mapping(bytes32 => VestingSchedule) private vestingSchedules; uint256 private vestingSchedulesTotalAmount; mapping(address => uint256) private holdersVestingCount; event Released(uint256 amount); event Revoked(); IERC20 immutable private _token; modifier onlyIfVestingScheduleExists(bytes32 vestingScheduleId) { require(vestingSchedules[vestingScheduleId].initialized == true); _; } modifier onlyIfVestingScheduleNotRevoked(bytes32 vestingScheduleId) { require(vestingSchedules[vestingScheduleId].initialized == true); require(vestingSchedules[vestingScheduleId].revoked == false); _; } constructor(address token_) { require(token_ != address(0x0)); _token = IERC20(token_); } receive() external payable {} fallback() external payable {} function getVestingSchedulesCountByBeneficiary(address _beneficiary) external view returns(uint256){ return holdersVestingCount[_beneficiary]; } function getVestingIdAtIndex(uint256 index) external view returns(bytes32){ require(index < getVestingSchedulesCount(), "TokenVesting: index out of bounds"); return vestingSchedulesIds[index]; } function getVestingScheduleByAddressAndIndex(address holder, uint256 index) external view returns(VestingSchedule memory){ return getVestingSchedule(computeVestingScheduleIdForAddressAndIndex(holder, index)); } function getVestingSchedulesTotalAmount() external view returns(uint256){ return vestingSchedulesTotalAmount; } function getToken() external view returns(address){ return address(_token); } function createVestingSchedule( address _beneficiary, uint256 _amount ) public onlyOwner{ require( this.getWithdrawableAmount() >= _amount, "TokenVesting: cannot create vesting schedule because not sufficient tokens" ); require(duration > 0, "TokenVesting: duration must be > 0"); require(_amount > 0, "TokenVesting: amount must be > 0"); require(slicePeriodSeconds >= 1, "TokenVesting: slicePeriodSeconds must be >= 1"); bytes32 vestingScheduleId = this.computeNextVestingScheduleIdForHolder(_beneficiary); vestingSchedules[vestingScheduleId] = VestingSchedule( true, _beneficiary, _amount, 0, false ); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.add(_amount); vestingSchedulesIds.push(vestingScheduleId); uint256 currentVestingCount = holdersVestingCount[_beneficiary]; holdersVestingCount[_beneficiary] = currentVestingCount.add(1); } function revoke(bytes32 vestingScheduleId) public onlyOwner onlyIfVestingScheduleNotRevoked(vestingScheduleId){ VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; require(revocable == true, "TokenVesting: vesting is not revocable"); uint256 vestedAmount = _computeReleasableAmount(vestingSchedule); if(vestedAmount > 0){ release(vestingScheduleId, vestedAmount); } uint256 unreleased = vestingSchedule.amountTotal.sub(vestingSchedule.released); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(unreleased); vestingSchedule.revoked = true; } function revoke(bytes32 vestingScheduleId) public onlyOwner onlyIfVestingScheduleNotRevoked(vestingScheduleId){ VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; require(revocable == true, "TokenVesting: vesting is not revocable"); uint256 vestedAmount = _computeReleasableAmount(vestingSchedule); if(vestedAmount > 0){ release(vestingScheduleId, vestedAmount); } uint256 unreleased = vestingSchedule.amountTotal.sub(vestingSchedule.released); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(unreleased); vestingSchedule.revoked = true; } function withdraw(uint256 amount) public nonReentrant onlyOwner{ require(this.getWithdrawableAmount() >= amount, "TokenVesting: not enough withdrawable funds"); _token.safeTransfer(owner(), amount); } function release( bytes32 vestingScheduleId, uint256 amount ) public nonReentrant onlyIfVestingScheduleNotRevoked(vestingScheduleId){ VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; bool isBeneficiary = msg.sender == vestingSchedule.beneficiary; bool isOwner = msg.sender == owner(); require( isBeneficiary || isOwner, "TokenVesting: only beneficiary and owner can release vested tokens" ); uint256 vestedAmount = _computeReleasableAmount(vestingSchedule); require(vestedAmount >= amount, "TokenVesting: cannot release tokens, not enough vested tokens"); vestingSchedule.released = vestingSchedule.released.add(amount); address payable beneficiaryPayable = payable(vestingSchedule.beneficiary); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(amount); _token.safeTransfer(beneficiaryPayable, amount); } function getVestingSchedulesCount() public view returns(uint256){ return vestingSchedulesIds.length; } function computeReleasableAmount(bytes32 vestingScheduleId) public onlyIfVestingScheduleNotRevoked(vestingScheduleId) view returns(uint256){ VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; return _computeReleasableAmount(vestingSchedule); } function getVestingSchedule(bytes32 vestingScheduleId) public view returns(VestingSchedule memory){ return vestingSchedules[vestingScheduleId]; } function getWithdrawableAmount() public view returns(uint256){ return _token.balanceOf(address(this)).sub(vestingSchedulesTotalAmount); } function computeNextVestingScheduleIdForHolder(address holder) public view returns(bytes32){ return computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder]); } function getLastVestingScheduleForHolder(address holder) public view returns(VestingSchedule memory){ return vestingSchedules[computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder] - 1)]; } function computeVestingScheduleIdForAddressAndIndex(address holder, uint256 index) public pure returns(bytes32){ return keccak256(abi.encodePacked(holder, index)); } function _computeReleasableAmount(VestingSchedule memory vestingSchedule) internal view returns(uint256){ uint256 currentTime = getCurrentTime(); if (vestingSchedule.revoked == true) { return 0; return vestingSchedule.amountTotal.sub(vestingSchedule.released); uint256 timeFromStart = currentTime.sub(start); uint secondsPerSlice = slicePeriodSeconds; uint256 vestedSlicePeriods = timeFromStart.div(secondsPerSlice); uint256 vestedSeconds = vestedSlicePeriods.mul(secondsPerSlice); uint256 vestedAmount = vestingSchedule.amountTotal.mul(vestedSeconds).div(duration); vestedAmount = vestedAmount.sub(vestingSchedule.released); return vestedAmount; } } function _computeReleasableAmount(VestingSchedule memory vestingSchedule) internal view returns(uint256){ uint256 currentTime = getCurrentTime(); if (vestingSchedule.revoked == true) { return 0; return vestingSchedule.amountTotal.sub(vestingSchedule.released); uint256 timeFromStart = currentTime.sub(start); uint secondsPerSlice = slicePeriodSeconds; uint256 vestedSlicePeriods = timeFromStart.div(secondsPerSlice); uint256 vestedSeconds = vestedSlicePeriods.mul(secondsPerSlice); uint256 vestedAmount = vestingSchedule.amountTotal.mul(vestedSeconds).div(duration); vestedAmount = vestedAmount.sub(vestingSchedule.released); return vestedAmount; } } } else if (currentTime >= start.add(duration)) { } else { function getCurrentTime() internal virtual view returns(uint256){ return block.timestamp; } function rescueToken(address _tokenAddress, uint256 _amount) external onlyOwner { IERC20(_tokenAddress).transfer(msg.sender, _amount); } function rescueETH(uint256 _amount) external onlyOwner { payable(msg.sender).transfer(_amount); } }
16,523,022
[ 1, 1345, 58, 10100, 19, 787, 813, 434, 326, 331, 10100, 3879, 927, 3048, 3879, 316, 3974, 3734, 434, 326, 331, 10100, 3879, 316, 3974, 3734, 434, 279, 2788, 3879, 364, 326, 331, 10100, 316, 3974, 2856, 578, 486, 326, 331, 10100, 353, 5588, 504, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 58, 10100, 353, 14223, 6914, 16, 868, 8230, 12514, 16709, 95, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 2254, 5034, 225, 787, 273, 404, 1105, 25, 3028, 29, 7677, 25, 31, 203, 565, 2254, 5034, 225, 927, 3048, 273, 404, 1105, 25, 3028, 29, 7677, 25, 31, 203, 565, 2254, 5034, 225, 3734, 273, 1381, 29242, 3784, 31, 203, 565, 2254, 5034, 2788, 5027, 6762, 273, 4752, 31, 203, 565, 1426, 5588, 504, 429, 273, 638, 31, 203, 203, 203, 203, 203, 565, 1958, 776, 10100, 6061, 95, 203, 3639, 1426, 6454, 31, 203, 3639, 1758, 225, 27641, 74, 14463, 814, 31, 203, 3639, 2254, 5034, 3844, 5269, 31, 203, 3639, 2254, 5034, 225, 15976, 31, 203, 3639, 1426, 22919, 31, 203, 565, 289, 203, 203, 203, 565, 1731, 1578, 8526, 3238, 331, 10100, 27073, 2673, 31, 203, 565, 2874, 12, 3890, 1578, 516, 776, 10100, 6061, 13, 3238, 331, 10100, 27073, 31, 203, 565, 2254, 5034, 3238, 331, 10100, 27073, 5269, 6275, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 366, 4665, 58, 10100, 1380, 31, 203, 203, 565, 871, 10819, 72, 12, 11890, 5034, 3844, 1769, 203, 565, 871, 14477, 14276, 5621, 203, 203, 565, 467, 654, 39, 3462, 11732, 3238, 389, 2316, 31, 203, 565, 9606, 1338, 2047, 58, 10100, 6061, 4002, 12, 3890, 1578, 331, 10100, 6061, 548, 13, 288, 203, 3639, 2583, 12, 90, 10100, 27073, 2 ]
pragma solidity ^0.4.20; contract WorkbenchBase { event WorkbenchContractCreated(string applicationName, string workflowName, address originatingAddress); event WorkbenchContractUpdated(string applicationName, string workflowName, string action, address originatingAddress); string internal ApplicationName; string internal WorkflowName; function WorkbenchBase(string applicationName, string workflowName) internal { ApplicationName = applicationName; WorkflowName = workflowName; } function ContractCreated() internal { WorkbenchContractCreated(ApplicationName, WorkflowName, msg.sender); } function ContractUpdated(string action) internal { WorkbenchContractUpdated(ApplicationName, WorkflowName, action, msg.sender); } } contract RoomThermostat is WorkbenchBase('RoomThermostat', 'RoomThermostat') { //Set of States enum StateType { Created, InUse} //List of properties StateType public State; address public Installer; address public User; int public TargetTemperature; enum ModeEnum {Off, Cool, Heat, Auto} ModeEnum public Mode; function RoomThermostat(address thermostatInstaller, address thermostatUser) public { Installer = thermostatInstaller; User = thermostatUser; TargetTemperature = 70; ContractCreated(); } function StartThermostat() public { if (Installer != msg.sender || State != StateType.Created) { revert(); } State = StateType.InUse; ContractUpdated('StartThermostat'); } function SetTargetTemperature(int targetTemperature) public { if (User != msg.sender || State != StateType.InUse) { revert(); } TargetTemperature = targetTemperature; ContractUpdated('SetTemperature'); } function SetMode(ModeEnum mode) public { if (User != msg.sender || State != StateType.InUse) { revert(); } Mode = mode; ContractUpdated('SetMode'); } }
Set of StatesList of properties
{ StateType public State; address public Installer; address public User; int public TargetTemperature; ModeEnum public Mode; function RoomThermostat(address thermostatInstaller, address thermostatUser) public enum StateType { Created, InUse} enum ModeEnum {Off, Cool, Heat, Auto} { Installer = thermostatInstaller; User = thermostatUser; TargetTemperature = 70; ContractCreated(); } function StartThermostat() public { if (Installer != msg.sender || State != StateType.Created) { revert(); } State = StateType.InUse; ContractUpdated('StartThermostat'); } function StartThermostat() public { if (Installer != msg.sender || State != StateType.Created) { revert(); } State = StateType.InUse; ContractUpdated('StartThermostat'); } function SetTargetTemperature(int targetTemperature) public { if (User != msg.sender || State != StateType.InUse) { revert(); } TargetTemperature = targetTemperature; ContractUpdated('SetTemperature'); } function SetTargetTemperature(int targetTemperature) public { if (User != msg.sender || State != StateType.InUse) { revert(); } TargetTemperature = targetTemperature; ContractUpdated('SetTemperature'); } function SetMode(ModeEnum mode) public { if (User != msg.sender || State != StateType.InUse) { revert(); } Mode = mode; ContractUpdated('SetMode'); } function SetMode(ModeEnum mode) public { if (User != msg.sender || State != StateType.InUse) { revert(); } Mode = mode; ContractUpdated('SetMode'); } }
7,240,752
[ 1, 694, 434, 29577, 682, 434, 1790, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 95, 203, 203, 202, 203, 202, 1119, 559, 1071, 3287, 31, 203, 202, 2867, 1071, 10284, 264, 31, 203, 202, 2867, 1071, 2177, 31, 203, 565, 509, 1071, 5916, 1837, 9289, 31, 203, 202, 2309, 3572, 1071, 225, 8126, 31, 203, 202, 203, 202, 915, 27535, 1315, 28055, 270, 12, 2867, 286, 28055, 270, 18678, 16, 1758, 286, 28055, 270, 1299, 13, 1071, 203, 202, 7924, 3287, 559, 288, 12953, 16, 657, 3727, 97, 203, 565, 2792, 8126, 3572, 288, 7210, 16, 385, 1371, 16, 8264, 270, 16, 8064, 97, 203, 202, 95, 203, 3639, 10284, 264, 273, 286, 28055, 270, 18678, 31, 203, 3639, 2177, 273, 286, 28055, 270, 1299, 31, 203, 3639, 5916, 1837, 9289, 273, 16647, 31, 203, 3639, 13456, 6119, 5621, 203, 565, 289, 203, 203, 202, 915, 3603, 1315, 28055, 270, 1435, 1071, 203, 202, 95, 203, 3639, 309, 261, 18678, 480, 1234, 18, 15330, 747, 3287, 480, 3287, 559, 18, 6119, 13, 203, 3639, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 203, 3639, 3287, 273, 3287, 559, 18, 15435, 31, 203, 3639, 13456, 7381, 2668, 1685, 1315, 28055, 270, 8284, 203, 565, 289, 203, 203, 202, 915, 3603, 1315, 28055, 270, 1435, 1071, 203, 202, 95, 203, 3639, 309, 261, 18678, 480, 1234, 18, 15330, 747, 3287, 480, 3287, 559, 18, 6119, 13, 203, 3639, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 203, 3639, 3287, 273, 3287, 559, 18, 15435, 31, 203, 3639, 13456, 7381, 2668, 1685, 1315, 28055, 270, 8284, 203, 565, 289, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-02-11 */ // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/apps-agent/contracts/standards/ERC1271.sol pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File: @aragon/apps-agent/contracts/SignatureValidator.sol pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // File: @aragon/apps-agent/contracts/standards/IERC165.sol pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, 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 ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/apps-agent/contracts/Agent.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-165 conformance /** * @notice Tells whether this contract supports a given ERC-165 interface * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/apps-voting/contracts/Voting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File: @aragon/ppf-contracts/contracts/IFeed.sol pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File: @aragon/apps-finance/contracts/Finance.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File: @aragon/apps-payroll/contracts/Payroll.sol pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File: @aragon/apps-token-manager/contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File: @aragon/apps-survey/contracts/Survey.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: @aragon/os/contracts/apm/Repo.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File: @aragon/os/contracts/apm/APMNamehash.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File: @aragon/os/contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: @aragon/os/contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: @aragon/os/contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: @aragon/os/contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File: @aragon/os/contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: @aragon/os/contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: @aragon/os/contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: @aragon/os/contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: @aragon/os/contracts/lib/ens/AbstractENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } // File: @aragon/os/contracts/lib/ens/ENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File: @aragon/os/contracts/lib/ens/PublicResolver.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File: @aragon/os/contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: @aragon/os/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: @aragon/os/contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: @aragon/os/contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File: @aragon/id/contracts/ens/IPublicResolver.sol pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File: @aragon/templates-shared/contracts/BaseTemplate.sol pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol pragma solidity 0.4.24; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol pragma solidity 0.4.24; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol pragma solidity 0.4.24; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; string public version = '0.3'; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply token total supply @param _connectorBalance total connector balance @param _connectorWeight connector weight, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in connector token @return purchase return amount */ function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _supply.mul(_depositAmount) / _connectorBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_connectorBalance); (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply token total supply @param _connectorBalance total connector @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000 @param _sellAmount sell amount, in the token itself @return sale return amount */ function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _connectorBalance; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _connectorBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight); uint256 temp1 = _connectorBalance.mul(result); uint256 temp2 = _connectorBalance << precision; return (temp1 - temp2) / result; } /** @dev given two connector balances/weights and a sell amount (in the first connector token), calculates the return for a conversion from the first connector token to the second connector token (in the second connector token) Formula: Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight)) @param _fromConnectorBalance input connector balance @param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000 @param _toConnectorBalance output connector balance @param _toConnectorWeight output connector weight, represented in ppm, 1-1000000 @param _amount input connector amount @return second connector amount */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { // validate input require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT); // special case for equal weights if (_fromConnectorWeight == _toConnectorWeight) return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromConnectorBalance.add(_amount); (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight); uint256 temp1 = _toConnectorBalance.mul(result); uint256 temp2 = _toConnectorBalance << precision; return (temp1 - temp2) / result; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' Detailed description: - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 - The natural logarithm of the input is calculated by summing up the intermediate results above - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalExp.py' Detailed description: - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible - The exponentiation of each binary exponent is given (pre-calculated) - The exponentiation of r is calculated via Taylor series for e^x, where x = r - The exponentiation of the input is calculated by multiplying the intermediate results above - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } } // File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol pragma solidity 0.4.24; contract IAragonFundraisingController { function openTrading() external; function updateTappedAmount(address _token) external; function collateralsToBeClaimed(address _collateral) public view returns (uint256); function balanceOf(address _who, address _token) public view returns (uint256); } // File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol pragma solidity 0.4.24; contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary (address indexed beneficiary); event UpdateFormula (address indexed formula); event UpdateFees (uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch ( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage) ; event CancelBatch (uint256 indexed id, address indexed collateral); event AddCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken (address indexed collateral); event UpdateCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open (); event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value); event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event UpdatePricing ( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded token] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING); controller = _controller; tokenManager = _tokenManager; token = ERC20(tokenManager.token()); formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) { Collateral storage collateral = collaterals[_collateral]; return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) { return _tokenManager.maxAccountTokens() == uint256(-1); } function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return ( _msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value ); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds tokenManager.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); tokenManager.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); tokenManager.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn); } function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } } // File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol pragma solidity 0.4.24; contract IPresale { function open() external; function close() external; function contribute(address _contributor, uint256 _value) external payable; function refund(address _contributor, uint256 _vestedPurchaseId) external; function contributionToTokens(uint256 _value) public view returns (uint256); function contributionToken() public view returns (address); } // File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol pragma solidity 0.4.24; contract ITap { function updateBeneficiary(address _beneficiary) external; function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external; function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external; function addTappedToken(address _token, uint256 _rate, uint256 _floor) external; function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external; function resetTappedToken(address _token) external; function updateTappedAmount(address _token) external; function withdraw(address _token) external; function getMaximumWithdrawal(address _token) public view returns (uint256); function rates(address _token) public view returns (uint256); } // File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol pragma solidity 0.4.24; contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE"); bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE"); bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE"); bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207; bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416; bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2; bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant TO_RESET_CAP = 10; string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS"; IPresale public presale; BatchedBancorMarketMaker public marketMaker; Agent public reserve; ITap public tap; address[] public toReset; /***** external functions *****/ /** * @notice Initialize Aragon Fundraising controller * @param _presale The address of the presale contract * @param _marketMaker The address of the market maker contract * @param _reserve The address of the reserve [pool] contract * @param _tap The address of the tap contract * @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open] */ function initialize( IPresale _presale, BatchedBancorMarketMaker _marketMaker, Agent _reserve, ITap _tap, address[] _toReset ) external onlyInit { require(isContract(_presale), ERROR_CONTRACT_IS_EOA); require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(isContract(_tap), ERROR_CONTRACT_IS_EOA); require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS); initialized(); presale = _presale; marketMaker = _marketMaker; reserve = _reserve; tap = _tap; for (uint256 i = 0; i < _toReset.length; i++) { require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS); toReset.push(_toReset[i]); } } /* generic settings related function */ /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { marketMaker.updateBeneficiary(_beneficiary); tap.updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { marketMaker.updateFees(_buyFeePct, _sellFeePct); } /* presale related functions */ /** * @notice Open presale */ function openPresale() external auth(OPEN_PRESALE_ROLE) { presale.open(); } /** * @notice Close presale and open trading */ function closePresale() external isInitialized { presale.close(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution token to be spent */ function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) { presale.contribute.value(msg.value)(msg.sender, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized { presale.refund(_contributor, _vestedPurchaseId); } /* market making related functions */ /** * @notice Open trading [enabling users to open buy and sell orders] */ function openTrading() external auth(OPEN_TRADING_ROLE) { for (uint256 i = 0; i < toReset.length; i++) { if (tap.rates(toReset[i]) != uint256(0)) { tap.resetTappedToken(toReset[i]); } } marketMaker.open(); } /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { marketMaker.openSellOrder(msg.sender, _collateral, _amount); } /** * @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimSellOrder(_seller, _batchId, _collateral); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage, uint256 _rate, uint256 _floor ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); if (_collateral != ETH) { reserve.addProtectedToken(_collateral); } if (_rate > 0) { tap.addTappedToken(_collateral, _rate, _floor); } } /** * @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past] * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function reAddCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { marketMaker.removeCollateralToken(_collateral); // the token should still be tapped to avoid being locked // the token should still be protected to avoid being spent } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* tap related functions */ /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) { tap.addTappedToken(_token, _rate, _floor); } /** * @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) { tap.updateTappedToken(_token, _rate, _floor); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { tap.updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary * @param _token The address of the token to be transfered from the reserve to the beneficiary */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { tap.withdraw(_token); } /***** public view functions *****/ function token() public view isInitialized returns (address) { return marketMaker.token(); } function contributionToken() public view isInitialized returns (address) { return presale.contributionToken(); } function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return tap.getMaximumWithdrawal(_token); } function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) { return marketMaker.collateralsToBeClaimed(_collateral); } function balanceOf(address _who, address _token) public view isInitialized returns (uint256) { uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who); if (_who == address(reserve)) { return balance.sub(tap.getMaximumWithdrawal(_token)); } else { return balance; } } /***** internal functions *****/ function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } } // File: @ablack/fundraising-presale/contracts/Presale.sol pragma solidity ^0.4.24; contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4 string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN"; string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL"; string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE"; string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD"; string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT"; string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE"; string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE"; string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE"; string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE"; string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED"; enum State { Pending, // presale is idle and pending to be started Funding, // presale has started and contributors can purchase tokens Refunding, // presale has not reached goal within period and contributors can claim refunds GoalReached, // presale has reached goal within period and trading is ready to be open Closed // presale has reached goal within period, has been closed and trading has been open } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; address public reserve; address public beneficiary; address public contributionToken; uint256 public goal; uint64 public period; uint256 public exchangeRate; uint64 public vestingCliffPeriod; uint64 public vestingCompletePeriod; uint256 public supplyOfferedPct; uint256 public fundingForBeneficiaryPct; uint64 public openDate; bool public isClosed; uint64 public vestingCliffDate; uint64 public vestingCompleteDate; uint256 public totalRaised; mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent) event SetOpenDate (uint64 date); event Close (); event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); /***** external function *****/ /** * @notice Initialize presale * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent] * @param _contributionToken The address of the token to be used to contribute * @param _goal The goal to be reached by the end of that presale [in contribution token wei] * @param _period The period within which to accept contribution for that presale * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM] * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM] * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM] * @param _openDate The date upon which that presale is to be open [ignored if 0] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, address _reserve, address _beneficiary, address _contributionToken, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY); require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN); require(_goal > 0, ERROR_INVALID_GOAL); require(_period > 0, ERROR_INVALID_TIME_PERIOD); require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE); require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD); require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD); require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT); require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT); initialized(); controller = _controller; tokenManager = _tokenManager; token = ERC20(_tokenManager.token()); reserve = _reserve; beneficiary = _beneficiary; contributionToken = _contributionToken; goal = _goal; period = _period; exchangeRate = _exchangeRate; vestingCliffPeriod = _vestingCliffPeriod; vestingCompletePeriod = _vestingCompletePeriod; supplyOfferedPct = _supplyOfferedPct; fundingForBeneficiaryPct = _fundingForBeneficiaryPct; if (_openDate != 0) { _setOpenDate(_openDate); } } /** * @notice Open presale [enabling users to contribute] */ function open() external auth(OPEN_ROLE) { require(state() == State.Pending, ERROR_INVALID_STATE); require(openDate == 0, ERROR_INVALID_STATE); _open(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _contributor The address of the contributor * @param _value The amount of contribution token to be spent */ function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) { require(state() == State.Funding, ERROR_INVALID_STATE); require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE); if (contributionToken == ETH) { require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE); } else { require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE); } _contribute(_contributor, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized { require(state() == State.Refunding, ERROR_INVALID_STATE); _refund(_contributor, _vestedPurchaseId); } /** * @notice Close presale and open trading */ function close() external nonReentrant isInitialized { require(state() == State.GoalReached, ERROR_INVALID_STATE); _close(); } /***** public view functions *****/ /** * @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution tokens to be used in that computation */ function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) { return _value.mul(exchangeRate).div(PPM); } function contributionToken() public view isInitialized returns (address) { return contributionToken; } /** * @notice Returns the current state of that presale */ function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; } else { return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; } else { return State.Refunding; } } /***** internal functions *****/ function _timeSinceOpen() internal view returns (uint64) { if (openDate == 0) { return 0; } else { return getTimestamp64().sub(openDate); } } function _setOpenDate(uint64 _date) internal { require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD); openDate = _date; _setVestingDatesWhenOpenDateIsKnown(); emit SetOpenDate(_date); } function _setVestingDatesWhenOpenDateIsKnown() internal { vestingCliffDate = openDate.add(vestingCliffPeriod); vestingCompleteDate = openDate.add(vestingCompletePeriod); } function _open() internal { _setOpenDate(getTimestamp64()); } function _contribute(address _contributor, uint256 _value) internal { uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value; if (contributionToken == ETH && _value > value) { msg.sender.transfer(_value.sub(value)); } // (contributor) ~~~> contribution tokens ~~~> (presale) if (contributionToken != ETH) { require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE); require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE); _transfer(contributionToken, _contributor, address(this), value); } // (mint ✨) ~~~> project tokens ~~~> (contributor) uint256 tokensToSell = contributionToTokens(value); tokenManager.issue(tokensToSell); uint256 vestedPurchaseId = tokenManager.assignVested( _contributor, tokensToSell, openDate, vestingCliffDate, vestingCompleteDate, true /* revokable */ ); totalRaised = totalRaised.add(value); // register contribution tokens spent in this purchase for a possible upcoming refund contributions[_contributor][vestedPurchaseId] = value; emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId); } function _refund(address _contributor, uint256 _vestedPurchaseId) internal { // recall how much contribution tokens are to be refund for this purchase uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId]; require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND); contributions[_contributor][_vestedPurchaseId] = 0; // (presale) ~~~> contribution tokens ~~~> (contributor) _transfer(contributionToken, address(this), _contributor, tokensToRefund); /** * NOTE * the following lines assume that _contributor has not transfered any of its vested tokens * for now TokenManager does not handle switching the transferrable status of its underlying token * there is thus no way to enforce non-transferrability during the presale phase only * this will be updated in a later version */ // (contributor) ~~~> project tokens ~~~> (token manager) (uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId); tokenManager.revokeVesting(_contributor, _vestedPurchaseId); // (token manager) ~~~> project tokens ~~~> (burn 💥) tokenManager.burn(address(tokenManager), tokensSold); emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId); } function _close() internal { isClosed = true; // (presale) ~~~> contribution tokens ~~~> (beneficiary) uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM); if (fundsForBeneficiary > 0) { _transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary); } // (presale) ~~~> contribution tokens ~~~> (reserve) uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this)); _transfer(contributionToken, address(this), reserve, tokensForReserve); // (mint ✨) ~~~> project tokens ~~~> (beneficiary) uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct); tokenManager.issue(tokensForBeneficiary); tokenManager.assignVested( beneficiary, tokensForBeneficiary, openDate, vestingCliffDate, vestingCompleteDate, false /* revokable */ ); // open trading controller.openTrading(); emit Close(); } function _transfer(address _token, address _from, address _to, uint256 _amount) internal { if (_token == ETH) { require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED); require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED); _to.transfer(_amount); } else { if (_from == address(this)) { require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } else { require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } } } } // File: @ablack/fundraising-tap/contracts/Tap.sol pragma solidity 0.4.24; contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE"); bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE"); bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE"); bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE"); bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30; bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc; bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd; bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288; bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT"; string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN"; string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE"; string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE"; string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED"; string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED"; string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO"; IAragonFundraisingController public controller; Vault public reserve; address public beneficiary; uint256 public batchBlocks; uint256 public maximumTapRateIncreasePct; uint256 public maximumTapFloorDecreasePct; mapping (address => uint256) public tappedAmounts; mapping (address => uint256) public rates; mapping (address => uint256) public floors; mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers] mapping (address => uint256) public lastTapUpdates; // timestamps event UpdateBeneficiary (address indexed beneficiary); event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct); event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct); event AddTappedToken (address indexed token, uint256 rate, uint256 floor); event RemoveTappedToken (address indexed token); event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor); event ResetTappedToken (address indexed token); event UpdateTappedAmount (address indexed token, uint256 tappedAmount); event Withdraw (address indexed token, uint256 amount); /***** external functions *****/ /** * @notice Initialize tap * @param _controller The address of the controller contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn] * @param _batchBlocks The number of blocks batches are to last * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE] * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _maximumTapRateIncreasePct, uint256 _maximumTapFloorDecreasePct ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS); require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); initialized(); controller = _controller; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; maximumTapRateIncreasePct = _maximumTapRateIncreasePct; maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { _updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) { require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN); require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); _addTappedToken(_token, _rate, _floor); } /** * @notice Remove tap for `_token.symbol(): string` * @param _token The address of the token to be un-tapped */ function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _removeTappedToken(_token); } /** * @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE); _updateTappedToken(_token, _rate, _floor); } /** * @notice Reset tap timestamps for `_token.symbol(): string` * @param _token The address of the token whose tap timestamps are to be reset */ function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _resetTappedToken(_token); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()` * @param _token The address of the token to be transfered */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); uint256 amount = _updateTappedAmount(_token); require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO); _withdraw(_token, amount); } /***** public view functions *****/ function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return _tappedAmount(_token); } function rates(address _token) public view isInitialized returns (uint256) { return rates[_token]; } /***** internal functions *****/ /* computation functions */ function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } function _tappedAmount(address _token) internal view returns (uint256) { uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]); uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve); uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]); uint256 tappedAmount = tappedAmounts[_token].add(flow); /** * whatever happens enough collateral should be * kept in the reserve pool to guarantee that * its balance is kept above the floor once * all pending sell orders are claimed */ /** * the reserve's balance is already below the balance to be kept * the tapped amount should be reset to zero */ if (balance <= toBeKept) { return 0; } /** * the reserve's balance minus the upcoming tap flow would be below the balance to be kept * the flow should be reduced to balance - toBeKept */ if (balance <= toBeKept.add(tappedAmount)) { return balance.sub(toBeKept); } /** * the reserve's balance minus the upcoming flow is above the balance to be kept * the flow can be added to the tapped amount */ return tappedAmount; } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) { return _maximumTapFloorDecreasePct <= PCT_BASE; } function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } function _tokenIsTapped(address _token) internal view returns (bool) { return rates[_token] != uint256(0); } function _tapRateIsValid(uint256 _rate) internal pure returns (bool) { return _rate != 0; } function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) { return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor); } function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) { uint256 rate = rates[_token]; if (_rate <= rate) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) { return true; } return false; } function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) { uint256 floor = floors[_token]; if (_floor >= floor) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (maximumTapFloorDecreasePct >= PCT_BASE) { return true; } if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) { return true; } return false; } /* state modifying functions */ function _updateTappedAmount(address _token) internal returns (uint256) { uint256 tappedAmount = _tappedAmount(_token); lastTappedAmountUpdates[_token] = _currentBatchId(); tappedAmounts[_token] = tappedAmount; emit UpdateTappedAmount(_token, tappedAmount); return tappedAmount; } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal { maximumTapRateIncreasePct = _maximumTapRateIncreasePct; emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal { maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * 1. if _token is tapped in the middle of a batch it will * reach the next batch faster than what it normally takes * to go through a batch [e.g. one block later] * 2. this will allow for a higher withdrawal than expected * a few blocks after _token is tapped * 3. this is not a problem because this extra amount is * static [at most rates[_token] * batchBlocks] and does * not increase in time */ rates[_token] = _rate; floors[_token] = _floor; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit AddTappedToken(_token, _rate, _floor); } function _removeTappedToken(address _token) internal { delete tappedAmounts[_token]; delete rates[_token]; delete floors[_token]; delete lastTappedAmountUpdates[_token]; delete lastTapUpdates[_token]; emit RemoveTappedToken(_token); } function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * withdraw before updating to keep the reserve * actual balance [balance - virtual withdrawal] * continuous in time [though a floor update can * still break this continuity] */ uint256 amount = _updateTappedAmount(_token); if (amount > 0) { _withdraw(_token, amount); } rates[_token] = _rate; floors[_token] = _floor; lastTapUpdates[_token] = getTimestamp(); emit UpdateTappedToken(_token, _rate, _floor); } function _resetTappedToken(address _token) internal { tappedAmounts[_token] = 0; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit ResetTappedToken(_token); } function _withdraw(address _token, uint256 _amount) internal { tappedAmounts[_token] = tappedAmounts[_token].sub(_amount); reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error emit Withdraw(_token, _amount); } } // File: contracts/AavegotchiTBCTemplate.sol pragma solidity 0.4.24; contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate { string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS"; string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE"; bool private constant BOARD_TRANSFERABLE = false; uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0); uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1); bool private constant SHARE_TRANSFERABLE = true; uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18); uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0); uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days); uint256 private constant BUY_FEE_PCT = 0; uint256 private constant SELL_FEE_PCT = 0; uint32 private constant DAI_RESERVE_RATIO = 333333; // 33% uint32 private constant ANT_RESERVE_RATIO = 10000; // 1% bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d; bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5; bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0; bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac; bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc; struct Cache { address dao; address boardTokenManager; address boardVoting; address vault; address finance; address shareVoting; address shareTokenManager; address reserve; address presale; address marketMaker; address tap; address controller; } address[] public collaterals; mapping (address => Cache) private cache; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID, address _dai, address _ant ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); require(isContract(_dai), ERROR_BAD_SETTINGS); require(isContract(_ant), ERROR_BAD_SETTINGS); require(_dai != _ant, ERROR_BAD_SETTINGS); collaterals.push(_dai); collaterals.push(_ant); } /***** external functions *****/ function prepareInstance( string _boardTokenName, string _boardTokenSymbol, address[] _boardMembers, uint64[3] _boardVotingSettings, uint64 _financePeriod ) external { require(_boardMembers.length > 0, ERROR_BAD_SETTINGS); require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS); // deploy DAO (Kernel dao, ACL acl) = _createDAO(); // deploy board token MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS); // install board apps TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod); // mint board tokens _mintTokens(acl, tm, _boardMembers, 1); // cache DAO _cacheDao(dao); } function installShareApps( string _shareTokenName, string _shareTokenSymbol, uint64[3] _shareVotingSettings ) external { require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS); _ensureBoardAppsCache(); Kernel dao = _daoCache(); // deploy share token MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS); // install share apps _installShareApps(dao, shareToken, _shareVotingSettings); // setup board apps permissions [now that share apps have been installed] _setupBoardPermissions(dao); } function installFundraisingApps( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) external { _ensureShareAppsCache(); Kernel dao = _daoCache(); // install fundraising apps _installFundraisingApps( dao, _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct ); // setup share apps permissions [now that fundraising apps have been installed] _setupSharePermissions(dao); // setup fundraising apps permissions _setupFundraisingPermissions(dao); } function finalizeInstance( string _id, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) external { require(bytes(_id).length > 0, ERROR_BAD_SETTINGS); require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS); require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS); require(_slippages.length == 2, ERROR_BAD_SETTINGS); _ensureFundraisingAppsCache(); Kernel dao = _daoCache(); ACL acl = ACL(dao.acl()); (, Voting shareVoting) = _shareAppsCache(); // setup collaterals _setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI); // setup EVM script registry permissions _createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting); // clear DAO permissions _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting); // register id _registerID(_id, address(dao)); // clear cache _clearCache(); } /***** internal apps installation functions *****/ function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod) internal returns (TokenManager) { TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _token, _votingSettings); Vault vault = _installVaultApp(_dao); Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod); _cacheBoardApps(tm, voting, vault, finance); return tm; } function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings) internal { TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings); _cacheShareApps(tm, voting); } function _installFundraisingApps( Kernel _dao, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) internal { _proxifyFundraisingApps(_dao); _initializePresale( _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); _initializeMarketMaker(_batchBlocks); _initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); _initializeController(); } function _proxifyFundraisingApps(Kernel _dao) internal { Agent reserve = _installNonDefaultAgentApp(_dao); Presale presale = Presale(_registerApp(_dao, PRESALE_ID)); BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID)); Tap tap = Tap(_registerApp(_dao, TAP_ID)); AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID)); _cacheFundraisingApps(reserve, presale, marketMaker, tap, controller); } /***** internal apps initialization functions *****/ function _initializePresale( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) internal { _presaleCache().initialize( _controllerCache(), _shareTMCache(), _reserveCache(), _vaultCache(), collaterals[0], _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); } function _initializeMarketMaker(uint256 _batchBlocks) internal { IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID)); (,, Vault beneficiary,) = _boardAppsCache(); (TokenManager shareTM,) = _shareAppsCache(); (Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache(); marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT); } function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal { (,, Vault beneficiary,) = _boardAppsCache(); (Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); } function _initializeController() internal { (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); address[] memory toReset = new address[](1); toReset[0] = collaterals[0]; controller.initialize(presale, marketMaker, reserve, tap, toReset); } /***** internal setup functions *****/ function _setupCollaterals( Kernel _dao, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) internal { ACL acl = ACL(_dao.acl()); (, Voting shareVoting) = _shareAppsCache(); (,,,, AragonFundraisingController controller) = _fundraisingAppsCache(); // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE()); // add DAI both as a protected collateral and a tapped token controller.addCollateralToken( collaterals[0], _virtualSupplies[0], _virtualBalances[0], DAI_RESERVE_RATIO, _slippages[0], _rateDAI, _floorDAI ); // add ANT as a protected collateral [but not as a tapped token] controller.addCollateralToken( collaterals[1], _virtualSupplies[1], _virtualBalances[1], ANT_RESERVE_RATIO, _slippages[1], 0, 0 ); // transfer ADD_COLLATERAL_TOKEN_ROLE _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); } /***** internal permissions functions *****/ function _setupBoardPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); // token manager _createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting); // voting _createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting); // vault _createVaultPermissions(acl, vault, finance, shareVoting); // finance _createFinancePermissions(acl, finance, boardVoting, shareVoting); _createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting); } function _setupSharePermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM,,,) = _boardAppsCache(); (TokenManager shareTM, Voting shareVoting) = _shareAppsCache(); (, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache(); // token manager address[] memory grantees = new address[](2); grantees[0] = address(marketMaker); grantees[1] = address(presale); acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting); _createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting); // voting _createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting); } function _setupFundraisingPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (, Voting boardVoting,,) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); // reserve address[] memory grantees = new address[](2); grantees[0] = address(tap); grantees[1] = address(marketMaker); acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting); acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting); _createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting); // presale acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting); acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting); // market maker acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting); // tap acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting); // controller // ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added] acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting); // acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting); acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting); } /***** internal cache functions *****/ function _cacheDao(Kernel _dao) internal { Cache storage c = cache[msg.sender]; c.dao = address(_dao); } function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal { Cache storage c = cache[msg.sender]; c.boardTokenManager = address(_boardTM); c.boardVoting = address(_boardVoting); c.vault = address(_vault); c.finance = address(_finance); } function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal { Cache storage c = cache[msg.sender]; c.shareTokenManager = address(_shareTM); c.shareVoting = address(_shareVoting); } function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal { Cache storage c = cache[msg.sender]; c.reserve = address(_reserve); c.presale = address(_presale); c.marketMaker = address(_marketMaker); c.tap = address(_tap); c.controller = address(_controller); } function _daoCache() internal view returns (Kernel dao) { Cache storage c = cache[msg.sender]; dao = Kernel(c.dao); } function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) { Cache storage c = cache[msg.sender]; boardTM = TokenManager(c.boardTokenManager); boardVoting = Voting(c.boardVoting); vault = Vault(c.vault); finance = Finance(c.finance); } function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); shareVoting = Voting(c.shareVoting); } function _fundraisingAppsCache() internal view returns ( Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller ) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); presale = Presale(c.presale); marketMaker = BatchedBancorMarketMaker(c.marketMaker); tap = Tap(c.tap); controller = AragonFundraisingController(c.controller); } function _clearCache() internal { Cache storage c = cache[msg.sender]; delete c.dao; delete c.boardTokenManager; delete c.boardVoting; delete c.vault; delete c.finance; delete c.shareVoting; delete c.shareTokenManager; delete c.reserve; delete c.presale; delete c.marketMaker; delete c.tap; delete c.controller; } /** * NOTE * the following functions are only needed for the presale * initialization function [which we can't compile otherwise * because of a `stack too deep` error] */ function _vaultCache() internal view returns (Vault vault) { Cache storage c = cache[msg.sender]; vault = Vault(c.vault); } function _shareTMCache() internal view returns (TokenManager shareTM) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); } function _reserveCache() internal view returns (Agent reserve) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); } function _presaleCache() internal view returns (Presale presale) { Cache storage c = cache[msg.sender]; presale = Presale(c.presale); } function _controllerCache() internal view returns (AragonFundraisingController controller) { Cache storage c = cache[msg.sender]; controller = AragonFundraisingController(c.controller); } /***** internal check functions *****/ function _ensureBoardAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.boardTokenManager != address(0) && c.boardVoting != address(0) && c.vault != address(0) && c.finance != address(0), ERROR_MISSING_CACHE ); } function _ensureShareAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.shareTokenManager != address(0) && c.shareVoting != address(0), ERROR_MISSING_CACHE ); } function _ensureFundraisingAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.reserve != address(0) && c.presale != address(0) && c.marketMaker != address(0) && c.tap != address(0) && c.controller != address(0), ERROR_MISSING_CACHE ); } /***** internal utils functions *****/ function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) { address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId)); emit InstalledApp(proxy, _appId); return proxy; } }
* @notice Returns the current state of that presale/
function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; return State.Refunding; } }
451,751
[ 1, 1356, 326, 783, 919, 434, 716, 4075, 5349, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 919, 1435, 1071, 1476, 25359, 1135, 261, 1119, 13, 288, 203, 3639, 309, 261, 3190, 1626, 422, 374, 747, 1696, 1626, 405, 11940, 1105, 10756, 288, 203, 5411, 327, 3287, 18, 8579, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 4963, 12649, 5918, 1545, 17683, 13, 288, 203, 5411, 309, 261, 291, 7395, 13, 288, 203, 7734, 327, 3287, 18, 7395, 31, 203, 7734, 327, 3287, 18, 27716, 23646, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 957, 9673, 3678, 1435, 411, 3879, 13, 288, 203, 5411, 327, 3287, 18, 42, 14351, 31, 203, 5411, 327, 3287, 18, 1957, 14351, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 /// @title The WizardsToken pseudo-random seed generator. // Modified version from NounsDAO. pragma solidity ^0.8.6; import {ISeeder} from "./ISeeder.sol"; import {IDescriptor} from "../descriptor/IDescriptor.sol"; contract Seeder is ISeeder { struct Counts { uint256 backgroundCount; uint256 skinsCount; uint256 mouthsCount; uint256 eyesCount; uint256 hatsCount; uint256 clothesCount; uint256 accessoryCount; uint256 bgItemCount; } /** * @notice Generate a pseudo-random Wizard seed using the previous blockhash and wizard ID. */ function generateSeed( uint256 wizardId, IDescriptor descriptor, bool isOneOfOne, uint48 oneOfOneIndex ) external view override returns (Seed memory) { if (isOneOfOne) { return Seed({ background: 0, skin: 0, bgItem: 0, accessory: 0, clothes: 0, mouth: 0, eyes: 0, hat: 0, oneOfOne: isOneOfOne, oneOfOneIndex: oneOfOneIndex }); } uint256 pseudorandomness = getRandomness(wizardId); Counts memory counts = getCounts(descriptor); uint256 accShift = getAccShift(wizardId); uint256 clothShift = getClothShift(wizardId); return Seed({ background: uint48( uint48(pseudorandomness) % counts.backgroundCount ), skin: uint48( uint48(pseudorandomness >> 48) % counts.skinsCount ), accessory: uint48( uint48(pseudorandomness >> accShift) % counts.accessoryCount ), mouth: uint48( uint48(pseudorandomness >> 144) % counts.mouthsCount ), eyes: uint48( uint48(pseudorandomness >> 192) % counts.eyesCount ), hat: uint48(uint48(pseudorandomness >> 144) % counts.hatsCount), bgItem: uint48( uint48(pseudorandomness >> accShift) % counts.bgItemCount ), clothes: uint48( uint48(pseudorandomness >> clothShift) % counts.clothesCount ), oneOfOne: isOneOfOne, oneOfOneIndex: oneOfOneIndex }); } function getCounts(IDescriptor descriptor) internal view returns (Counts memory) { return Counts({ backgroundCount: descriptor.backgroundCount(), skinsCount: descriptor.skinsCount(), mouthsCount: descriptor.mouthsCount(), eyesCount: descriptor.eyesCount(), hatsCount: descriptor.hatsCount(), clothesCount: descriptor.clothesCount(), accessoryCount: descriptor.accessoryCount(), bgItemCount: descriptor.bgItemsCount() }); } function getRandomness(uint256 wizardId) internal view returns (uint256) { uint256 pseudorandomness = uint256( keccak256( abi.encodePacked( blockhash(block.number - 1), wizardId, block.difficulty, block.coinbase ) ) ); return pseudorandomness; } function getAccShift(uint256 wizardId) internal pure returns (uint256) { uint256 rem = wizardId % 2; uint256 shift = (rem == 0) ? 96 : 192; return shift; } function getClothShift(uint256 wizardId) internal pure returns (uint256) { uint256 rem = wizardId % 2; uint256 clothShift = (rem == 0) ? 48 : 144; return clothShift; } } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for Seeder pragma solidity ^0.8.6; import { IDescriptor } from '../descriptor/IDescriptor.sol'; // "Skin", "Cloth", "Eye", "Mouth", "Acc", "Item", "Hat" interface ISeeder { struct Seed { uint48 background; uint48 skin; uint48 clothes; uint48 eyes; uint48 mouth; uint48 accessory; uint48 bgItem; uint48 hat; bool oneOfOne; uint48 oneOfOneIndex; } function generateSeed(uint256 wizardId, IDescriptor descriptor, bool isOneOfOne, uint48 isOneOfOneIndex) external view returns (Seed memory); } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for Descriptor pragma solidity ^0.8.6; import { ISeeder } from '../seeder/ISeeder.sol'; interface IDescriptor { event PartsLocked(); event DataURIToggled(bool enabled); event BaseURIUpdated(string baseURI); function arePartsLocked() external returns (bool); function isDataURIEnabled() external returns (bool); function baseURI() external returns (string memory); function palettes(uint8 paletteIndex, uint256 colorIndex) external view returns (string memory); function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external; function addColorToPalette(uint8 paletteIndex, string calldata color) external; function backgrounds(uint256 index) external view returns (string memory); function backgroundCount() external view returns (uint256); function addManyBackgrounds(string[] calldata backgrounds) external; function addBackground(string calldata background) external; function oneOfOnes(uint256 index) external view returns (bytes memory); function oneOfOnesCount() external view returns (uint256); function addOneOfOne(bytes calldata _oneOfOne) external; function addManyOneOfOnes(bytes[] calldata _oneOfOnes) external; function skins(uint256 index) external view returns (bytes memory); function skinsCount() external view returns (uint256); function addManySkins(bytes[] calldata skins) external; function addSkin(bytes calldata skin) external; function hats(uint256 index) external view returns (bytes memory); function hatsCount() external view returns (uint256); function addManyHats(bytes[] calldata hats) external; function addHat(bytes calldata hat) external; function clothes(uint256 index) external view returns (bytes memory); function clothesCount() external view returns (uint256); function addManyClothes(bytes[] calldata ears) external; function addClothes(bytes calldata ear) external; function mouths(uint256 index) external view returns (bytes memory); function mouthsCount() external view returns (uint256); function addManyMouths(bytes[] calldata mouths) external; function addMouth(bytes calldata mouth) external; function eyes(uint256 index) external view returns (bytes memory); function eyesCount() external view returns (uint256); function addManyEyes(bytes[] calldata eyes) external; function addEyes(bytes calldata eye) external; function accessory(uint256 index) external view returns (bytes memory); function accessoryCount() external view returns (uint256); function addManyAccessories(bytes[] calldata noses) external; function addAccessory(bytes calldata nose) external; function bgItems(uint256 index) external view returns (bytes memory); function bgItemsCount() external view returns (uint256); function addManyBgItems(bytes[] calldata noses) external; function addBgItem(bytes calldata nose) external; function lockParts() external; function toggleDataURIEnabled() external; function setBaseURI(string calldata baseURI) external; function tokenURI(uint256 tokenId, ISeeder.Seed memory seed) external view returns (string memory); function dataURI(uint256 tokenId, ISeeder.Seed memory seed) external view returns (string memory); function genericDataURI( string calldata name, string calldata description, ISeeder.Seed memory seed ) external view returns (string memory); function generateSVGImage(ISeeder.Seed memory seed) external view returns (string memory); }
* @notice Generate a pseudo-random Wizard seed using the previous blockhash and wizard ID./
function generateSeed( uint256 wizardId, IDescriptor descriptor, bool isOneOfOne, uint48 oneOfOneIndex ) external view override returns (Seed memory) { if (isOneOfOne) { return Seed({ background: 0, skin: 0, bgItem: 0, accessory: 0, clothes: 0, mouth: 0, eyes: 0, hat: 0, oneOfOne: isOneOfOne, oneOfOneIndex: oneOfOneIndex }); } uint256 pseudorandomness = getRandomness(wizardId); Counts memory counts = getCounts(descriptor); uint256 accShift = getAccShift(wizardId); uint256 clothShift = getClothShift(wizardId); return Seed({ background: uint48( uint48(pseudorandomness) % counts.backgroundCount ), skin: uint48( uint48(pseudorandomness >> 48) % counts.skinsCount ), accessory: uint48( uint48(pseudorandomness >> accShift) % counts.accessoryCount ), mouth: uint48( uint48(pseudorandomness >> 144) % counts.mouthsCount ), eyes: uint48( uint48(pseudorandomness >> 192) % counts.eyesCount ), hat: uint48(uint48(pseudorandomness >> 144) % counts.hatsCount), bgItem: uint48( uint48(pseudorandomness >> accShift) % counts.bgItemCount ), clothes: uint48( uint48(pseudorandomness >> clothShift) % counts.clothesCount ), oneOfOne: isOneOfOne, oneOfOneIndex: oneOfOneIndex }); }
5,826,053
[ 1, 4625, 279, 12454, 17, 9188, 678, 13412, 5009, 1450, 326, 2416, 1203, 2816, 471, 24204, 1599, 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 ]
[ 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, 2103, 12702, 12, 203, 3639, 2254, 5034, 24204, 548, 16, 203, 3639, 1599, 2263, 4950, 16, 203, 3639, 1426, 353, 3335, 951, 3335, 16, 203, 3639, 2254, 8875, 1245, 951, 3335, 1016, 203, 565, 262, 3903, 1476, 3849, 1135, 261, 12702, 3778, 13, 288, 203, 3639, 309, 261, 291, 3335, 951, 3335, 13, 288, 203, 5411, 327, 203, 7734, 28065, 12590, 203, 10792, 5412, 30, 374, 16, 203, 10792, 18705, 30, 374, 16, 203, 10792, 7611, 1180, 30, 374, 16, 203, 10792, 2006, 630, 30, 374, 16, 203, 10792, 927, 10370, 281, 30, 374, 16, 203, 10792, 312, 15347, 30, 374, 16, 203, 10792, 12739, 281, 30, 374, 16, 203, 10792, 366, 270, 30, 374, 16, 203, 10792, 1245, 951, 3335, 30, 353, 3335, 951, 3335, 16, 203, 10792, 1245, 951, 3335, 1016, 30, 1245, 951, 3335, 1016, 203, 7734, 15549, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 29606, 280, 2111, 4496, 273, 20581, 4496, 12, 31837, 548, 1769, 203, 3639, 6974, 87, 3778, 6880, 273, 336, 9211, 12, 12628, 1769, 203, 3639, 2254, 5034, 4078, 10544, 273, 4506, 952, 10544, 12, 31837, 548, 1769, 203, 3639, 2254, 5034, 927, 10370, 10544, 273, 13674, 10370, 10544, 12, 31837, 548, 1769, 203, 203, 3639, 327, 203, 5411, 28065, 12590, 203, 7734, 5412, 30, 2254, 8875, 12, 203, 10792, 2254, 8875, 12, 84, 23715, 280, 2111, 4496, 13, 738, 6880, 18, 9342, 1380, 203, 7734, 262, 16, 203, 7734, 18705, 30, 2254, 8875, 12, 203, 10792, 2254, 8875, 12, 84, 23715, 280, 2111, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './ERC721B.sol'; import './Ownable.sol'; import './Strings.sol'; /** * @title CryptoSea Friends contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ library Math { function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } } interface IFreeFromUpTo { function freeUpTo(uint256 value) external returns (uint256); function freeFrom(address from, uint256 value) external returns (uint256); function freeFromUpTo(address from, uint256 value) external returns (uint256 freed); } contract CryptoSeaFriends is Ownable, ERC721B { IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); using Strings for uint256; string private _tokenBaseURI; uint256 public mintPrice; uint256 public maxMintAmountPerTX; uint256 public MAX_CSF_SUPPLY; bool public isPresale = true; bool public isSale; mapping (address => bool) public whitelist; address private wallet1 = 0xB6EF1661d0bBD987AAab23bAa1752A236d8Ab785; address private wallet2 = 0xC0f501636659b483aA0f00FEBD933d1fb3c8CeBE; modifier discountCHI(uint256 chiAmount) { if (chiAmount > 0) { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; uint256 minAmount = Math.min((gasSpent + 14154) / 41947, chiAmount); // TokenInterface(address(chi)).approve(address(this), minAmount); // chi.freeFromUpTo(_msgSender(), Math.min((gasSpent + 14154) / 41947, chiAmount)); chi.freeUpTo(minAmount); } else { _; } } constructor() ERC721B("CryptoSea Friends", "CSF") { MAX_CSF_SUPPLY = 5555; mintPrice = 0.05 ether; maxMintAmountPerTX = 7; } /** * Check if certain token id is exists. */ function exists(uint256 _tokenId) public view returns (bool) { return _exists(_tokenId); } /** * Set mint price for a CryptoSea Friend. */ function setMintPrice(uint256 _mintPrice) external onlyOwner { mintPrice = _mintPrice; } /** * Set maximum count to mint per one tx. */ function setMaxToMintPerTX(uint256 _maxMintAmountPerTX) external onlyOwner { maxMintAmountPerTX = _maxMintAmountPerTX; } /* * Set base URI */ function setBaseURI(string memory baseURI) external onlyOwner { _tokenBaseURI = baseURI; } /* * Set sale status */ function setSaleStatus(bool _isSale) external onlyOwner { isSale = _isSale; } /* * Set presale status */ function changePresaleStatus(bool _isPresale) external onlyOwner { isPresale = _isPresale; } /* * Whitelist wallets */ function addWhitelist(address[] memory walletList) external onlyOwner { for (uint i=0; i<walletList.length; i++) { whitelist[walletList[i]] = true; } } /** * Reserve CryptoSea Friend by owner */ function reserveCSF(address to, uint256 count) external onlyOwner discountCHI(count * 5) { require(to != address(0), "Invalid address to reserve."); uint256 supply = _owners.length; require(supply + count <= MAX_CSF_SUPPLY, "Reserve would exceed max supply"); for (uint256 i = 0; i < count; i++) { _safeMint(to, supply++ ); } } function tokenURI(uint256 tokenId) external view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(_tokenBaseURI, tokenId.toString())); } /** * Mint CryptoSea Friend */ function mintCSF(uint256 count) external payable discountCHI(count * 5) { require(isSale, "Sale must be active to mint"); require(count <= maxMintAmountPerTX, "Invalid amount to mint per tx"); require(mintPrice * count <= msg.value, "Ether value sent is not correct"); require(isPresale || whitelist[_msgSender()], "You are not in whitelist."); uint256 supply = _owners.length; require(supply + count <= MAX_CSF_SUPPLY, "Purchase would exceed max supply"); for(uint256 i = 0; i < count; i++) { _mint( msg.sender, supply++); } } function withdraw() external onlyOwner { payable(wallet1).transfer(address(this).balance * 30 / 100); payable(wallet2).transfer(address(this).balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Address.sol"; import "./Context.sol"; import "./ERC165.sol"; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; abstract contract ERC721B is Context, ERC165, IERC721, IERC721Metadata { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address address[] internal _owners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @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"); uint count = 0; uint length = _owners.length; for( uint i = 0; i < length; ++i ){ if( owner == _owners[i] ){ ++count; } } delete length; return count; } /** * @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 {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721B.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 tokenId < _owners.length && _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 = ERC721B.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); _owners.push(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 = ERC721B.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); 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(ERC721B.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); _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(ERC721B.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; import './IERC165.sol'; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './IERC721.sol'; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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); }
* Set mint price for a CryptoSea Friend./
function setMintPrice(uint256 _mintPrice) external onlyOwner { mintPrice = _mintPrice; }
71,043
[ 1, 694, 312, 474, 6205, 364, 279, 15629, 1761, 69, 478, 7522, 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, 15430, 474, 5147, 12, 11890, 5034, 389, 81, 474, 5147, 13, 3903, 1338, 5541, 288, 203, 3639, 312, 474, 5147, 273, 389, 81, 474, 5147, 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 ]
/* Copyright 2019 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.5.9; pragma experimental ABIEncoderV2; import "../src/interfaces/IStructs.sol"; import "./TestStakingNoWETH.sol"; contract TestMixinStake is TestStakingNoWETH { event ZrxVaultDepositFrom( address staker, uint256 amount ); event ZrxVaultWithdrawFrom( address staker, uint256 amount ); event MoveStakeStorage( bytes32 fromBalanceSlot, bytes32 toBalanceSlot, uint256 amount ); event IncreaseCurrentAndNextBalance( bytes32 balanceSlot, uint256 amount ); event DecreaseCurrentAndNextBalance( bytes32 balanceSlot, uint256 amount ); event IncreaseNextBalance( bytes32 balanceSlot, uint256 amount ); event DecreaseNextBalance( bytes32 balanceSlot, uint256 amount ); event WithdrawAndSyncDelegatorRewards( bytes32 poolId, address delegator ); /// @dev Advance the epoch counter. function advanceEpoch() external { currentEpoch += 1; } /// @dev `IZrxVault.depositFrom` function depositFrom(address staker, uint256 amount) external { emit ZrxVaultDepositFrom(staker, amount); } /// @dev `IZrxVault.withdrawFrom` function withdrawFrom(address staker, uint256 amount) external { emit ZrxVaultWithdrawFrom(staker, amount); } function getDelegatedStakeByPoolIdSlot(bytes32 poolId) external view returns (bytes32 slot) { return _getPtrSlot(_delegatedStakeByPoolId[poolId]); } function getDelegatedStakeToPoolByOwnerSlot(bytes32 poolId, address staker) external view returns (bytes32 slot) { return _getPtrSlot(_delegatedStakeToPoolByOwner[staker][poolId]); } function getGlobalStakeByStatusSlot(IStructs.StakeStatus status) external view returns (bytes32 slot) { return _getPtrSlot(_globalStakeByStatus[uint8(status)]); } function getOwnerStakeByStatusSlot(address owner, IStructs.StakeStatus status) external view returns (bytes32 slot) { return _getPtrSlot(_ownerStakeByStatus[uint8(status)][owner]); } /// @dev Set `_ownerStakeByStatus` function setOwnerStakeByStatus( address owner, IStructs.StakeStatus status, IStructs.StoredBalance memory stake ) public { _ownerStakeByStatus[uint8(status)][owner] = stake; } /// @dev Overridden to use this contract as the ZRX vault. function getZrxVault() public view returns (IZrxVault zrxVault) { return IZrxVault(address(this)); } /// @dev Overridden to only emit an event. function _withdrawAndSyncDelegatorRewards( bytes32 poolId, address member ) internal { emit WithdrawAndSyncDelegatorRewards(poolId, member); } /// @dev Overridden to only emit an event. function _moveStake( IStructs.StoredBalance storage fromPtr, IStructs.StoredBalance storage toPtr, uint256 amount ) internal { emit MoveStakeStorage( _getPtrSlot(fromPtr), _getPtrSlot(toPtr), amount ); } /// @dev Overridden to only emit an event. function _increaseCurrentAndNextBalance( IStructs.StoredBalance storage balancePtr, uint256 amount ) internal { emit IncreaseCurrentAndNextBalance( _getPtrSlot(balancePtr), amount ); } /// @dev Overridden to only emit an event. function _decreaseCurrentAndNextBalance( IStructs.StoredBalance storage balancePtr, uint256 amount ) internal { emit DecreaseCurrentAndNextBalance( _getPtrSlot(balancePtr), amount ); } /// @dev Overridden to only emit an event. function _increaseNextBalance( IStructs.StoredBalance storage balancePtr, uint256 amount ) internal { emit IncreaseNextBalance( _getPtrSlot(balancePtr), amount ); } /// @dev Overridden to only emit an event. function _decreaseNextBalance( IStructs.StoredBalance storage balancePtr, uint256 amount ) internal { emit DecreaseNextBalance( _getPtrSlot(balancePtr), amount ); } /// @dev Overridden to just return the input. function _loadCurrentBalance(IStructs.StoredBalance storage balancePtr) internal view returns (IStructs.StoredBalance memory balance) { balance = balancePtr; } /// @dev Throws if poolId == 0x0 function _assertStakingPoolExists(bytes32 poolId) internal view { require(poolId != bytes32(0), "INVALID_POOL"); } // solhint-disable-next-line function _getPtrSlot(IStructs.StoredBalance storage ptr) private pure returns (bytes32 offset) { assembly { offset := ptr_slot } } }
@dev Throws if poolId == 0x0
function _assertStakingPoolExists(bytes32 poolId) internal view { require(poolId != bytes32(0), "INVALID_POOL"); }
12,560,113
[ 1, 21845, 309, 2845, 548, 422, 374, 92, 20, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 11231, 510, 6159, 2864, 4002, 12, 3890, 1578, 2845, 548, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 565, 288, 203, 3639, 2583, 12, 6011, 548, 480, 1731, 1578, 12, 20, 3631, 315, 9347, 67, 20339, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract queryMeta { //Model metadata of EMR struct EMRMeta { uint owner; //patient ID; public will have getter and setter function automatically string timestamp; uint allowedRole; } //Store EMRMetas mapping (uint => EMRMeta) public EMRMetas; //store EMRMetas count uint public EMRMetasCount; struct User{ string name; //name of doctor or patient uint id; uint roleNum; /* consider doctor only for the time being: 1 -> doctor 2 -> analyzer 3 -> insurance 4-> patient */ } //Store roles mapping (uint => User) public users; //store EMRMetas count uint public usersCount; //update EMRMeta event event updateMetaEvent ( uint indexed _owner ); /* * Contructor, will run whenever we deploy the contract to the blockchain * (initialized contract upon migration) * same name as the contract */ function queryMeta () public { //initialize users directly //users[0] = User("Alice", 888, 1); //doctor //users[1] = User("Bob", 87, 4); //a patient addUser("Alice", 888, 1);//doctor addUser("Bob", 87, 4);//a patient //initialize EMRMetas directly //EMRMetas[0] = EMRMeta(123, "20181118", 1); //EMRMetas[1] = EMRMeta(456, "20181119", 4); addMetas(123, "20181118", 1); addMetas(456, "20181119", 4); } //add a new medical metadata function addMetas (uint _owner, string _timestamp, uint _allowedRole) public{ //addMetas string _timestamp can be get automatically later (solidity date) //check role to be allowed to addEMRMetas //require(roles[msg.sender] == 1); //only a doctor can addEMRMetas now //here msg.sender is an address, msg.sender to identify the address of who calling this function /********************************************************************************/ /*******Here we should consider to add "medical data" to cloud (dejima)**********/ /********************************************************************************/ EMRMetasCount ++; EMRMetas[EMRMetasCount] = EMRMeta(_owner, _timestamp, _allowedRole); } //add a new person who belongs a role function addUser (string _name, uint _id, uint _roleNum) private { //check the priviledge to add User // add users in the cloud usersCount ++; users[usersCount] = User(_name, _id, _roleNum); } //update an existing medical metadata, suppose will change the allowedRole function updateMetas (uint _owner) public { //updateMetas string _timestamp can be get automatically later //check role to be allowed to updateEMRMetas //require(roles[msg.sender] == 1); //only a doctor can updateEMRMetas now //here msg.sender is an address, msg.sender to identify the address of who calling this function /********************************************************************************/ /*******Here we should consider to update "medical data" to cloud (dejima)**********/ /********************************************************************************/ for (uint i = 1; i <= EMRMetasCount; i++) { if(EMRMetas[i].owner == _owner) EMRMetas[i].allowedRole = 3; } // trigger updateMeta Event updateMetaEvent(_owner); } /*deleteEMRMetas string _timestamp can be get automatically later function deleteEMRMetas (uint _owner, string _timestamp) private{ //check role to be allowed to deleteEMRMetas require(roles[msg.sender] == 1); //only a doctor can deleteEMRMetas now /********************************************************************************/ /*******Here we should consider to delete "medical data" to cloud (dejima)*******/ /********************************************************************************/ /* If a metadata is deleted, the owner ID is assigned to 0 (if this, later will need to fresh EMRMetas to remove unuseful EMRMetas) //search EMRMetas using _owner //assign 0 to this _owner field //decrement the EMRMetasCount by 1 }*/ }
Model metadata of EMR
contract queryMeta { struct EMRMeta { string timestamp; uint allowedRole; } mapping (uint => EMRMeta) public EMRMetas; uint public EMRMetasCount; struct User{ uint id; uint roleNum; /* consider doctor only for the time being: 1 -> doctor 2 -> analyzer 3 -> insurance 4-> patient */ } uint indexed _owner ); mapping (uint => User) public users; uint public usersCount; event updateMetaEvent ( function queryMeta () public { addMetas(123, "20181118", 1); addMetas(456, "20181119", 4); } function addMetas (uint _owner, string _timestamp, uint _allowedRole) public{ EMRMetasCount ++; EMRMetas[EMRMetasCount] = EMRMeta(_owner, _timestamp, _allowedRole); } function addUser (string _name, uint _id, uint _roleNum) private { usersCount ++; users[usersCount] = User(_name, _id, _roleNum); } function updateMetas (uint _owner) public { for (uint i = 1; i <= EMRMetasCount; i++) { if(EMRMetas[i].owner == _owner) EMRMetas[i].allowedRole = 3; } } function updateMetas (uint _owner) public { for (uint i = 1; i <= EMRMetasCount; i++) { if(EMRMetas[i].owner == _owner) EMRMetas[i].allowedRole = 3; } } updateMetaEvent(_owner); function deleteEMRMetas (uint _owner, string _timestamp) private{ If a metadata is deleted, the owner ID is assigned to 0 (if this, later will need to fresh EMRMetas to remove unuseful EMRMetas) }*/ }
1,086,834
[ 1, 1488, 1982, 434, 7141, 54, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 843, 2781, 288, 203, 203, 565, 1958, 7141, 54, 2781, 288, 203, 3639, 533, 2858, 31, 203, 3639, 2254, 2935, 2996, 31, 203, 565, 289, 203, 203, 203, 565, 2874, 261, 11890, 516, 7141, 54, 2781, 13, 1071, 7141, 8717, 29960, 31, 203, 565, 2254, 1071, 7141, 8717, 29960, 1380, 31, 203, 565, 1958, 2177, 95, 203, 1377, 2254, 612, 31, 203, 1377, 2254, 2478, 2578, 31, 1748, 203, 10792, 5260, 741, 30206, 1338, 364, 326, 813, 3832, 30, 203, 8227, 404, 317, 741, 30206, 203, 8227, 576, 317, 15116, 203, 8227, 890, 317, 2763, 295, 1359, 203, 8227, 1059, 2122, 225, 18608, 203, 13491, 1195, 203, 565, 289, 203, 203, 203, 3639, 2254, 8808, 389, 8443, 203, 565, 11272, 203, 203, 203, 565, 2874, 261, 11890, 516, 2177, 13, 1071, 3677, 31, 203, 565, 2254, 1071, 3677, 1380, 31, 203, 565, 871, 1089, 2781, 1133, 261, 203, 565, 445, 843, 2781, 1832, 1071, 288, 203, 203, 203, 203, 6647, 527, 30853, 12, 12936, 16, 315, 21849, 2499, 2643, 3113, 404, 1769, 203, 6647, 527, 30853, 12, 24, 4313, 16, 315, 21849, 2499, 3657, 3113, 1059, 1769, 203, 565, 289, 203, 203, 565, 445, 527, 30853, 261, 11890, 389, 8443, 16, 533, 389, 5508, 16, 2254, 389, 8151, 2996, 13, 1071, 95, 203, 203, 203, 203, 3639, 7141, 8717, 29960, 1380, 965, 31, 203, 203, 3639, 7141, 8717, 29960, 63, 3375, 8717, 29960, 1380, 65, 273, 7141, 54, 2781, 24899, 8443, 16, 389, 5508, 16, 389, 8151, 2996, 1769, 203, 203, 203, 565, 2 ]
pragma solidity ^ 0.4.24; contract ERC20Interface { function totalSupply() public constant returns(uint); function balanceOf(address tokenOwner) public constant returns(uint balance); function allowance(address tokenOwner, address spender) public constant returns(uint remaining); function transfer(address to, uint tokens) public returns(bool success); function approve(address spender, uint tokens) public returns(bool success); function transferFrom(address from, address to, uint tokens) public returns(bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // 核心类 // ---------------------------------------------------------------------------- contract Oasis is ERC20Interface, Owned { string public symbol; string public name; uint8 public decimals; uint _totalSupply; //address public owner; bool public actived; struct keyconf{ uint basekeynum;//4500 uint basekeysub;//500 uint usedkeynum;//0 uint startprice;//0.01 uint keyprice;//0.01 uint startbasekeynum;//4500 uint[] keyidarr; uint currentkeyid; } keyconf private keyconfig; uint[] public worksdata; uint public onceOuttime; uint8 public per; //uint[] public mans; uint[] public mms; uint[] public pers; uint[] public prizeper; uint[] public prizelevelsuns; uint[] public prizelevelmans; uint[] public prizelevelsunsday; uint[] public prizelevelmoneyday; uint[] public prizeactivetime; address[] public mansdata; uint[] public moneydata; uint[] public timedata; uint public pubper; uint public subper; uint public luckyper; uint public lastmoney; uint public lastper; uint public lasttime; uint public sellkeyper; //bool public isend; uint public tags; //uint public opentime; uint public runper; uint public sellper; uint public sellupper; uint public sysday; uint public cksysday; //uint public nulldayeth; mapping(uint => mapping(uint => uint)) allprize; //uint public allprizeused; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; struct usercan{ uint eths; uint used; uint len; uint[] times; uint[] moneys; uint[] amounts; } mapping(address => usercan) mycan; mapping(address => usercan) myrun; struct userdata{ uint systemtag; uint tzs; uint usereths; uint userethsused; uint mylevelid; uint mykeysid; uint mykeyeths; uint prizecount; address fromaddr; uint sun1; uint sun2; uint sun3; //uint mysunmoney; mapping(uint => uint) mysunsdaynum; mapping(uint => uint) myprizedayget; mapping(uint => uint) daysusereths; mapping(uint => uint) daysuserdraws; mapping(uint => uint) daysuserlucky; mapping(uint => uint) levelget; mapping(uint => bool) hascountprice; } mapping(address => userdata) my; mapping(address => uint) mysunmoney; uint[] public leveldata; mapping(uint => mapping(uint => uint)) public userlevelsnum; //与用户钥匙id对应 mapping(uint => address) public myidkeys; //all once day get all mapping(uint => uint) public daysgeteths; mapping(uint => uint) public dayseths; //user once day pay mapping(uint => uint) public daysysdraws; struct tagsdata{ uint ethnum;//用户总资产 uint sysethnum;//系统总eth uint userethnum;//用户总eth uint userethnumused;//用户总eth uint syskeynum;//系统总key } mapping(uint => tagsdata) tg; mapping(address => bool) mangeruser; mapping(address => uint) mangerallowed; string private version; string private downurl; string private notices; uint public hasusednum; /* 通知 */ event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event FrozenFunds(address target, bool frozen); event ethchange(address indexed from, address indexed to, uint tokens); modifier onlySystemStart() { require(actived == true); require(tags == my[msg.sender].systemtag); require(!frozenAccount[msg.sender]); _; } constructor() public { symbol = "OASIS"; name = "Oasis"; decimals = 18; _totalSupply = 100000000 ether; actived = true; tags = 0; tg[0] = tagsdata(0,0,0,0,0); keyconfig.currentkeyid = 0; keyconfig.keyidarr = [10055555,20055555,30055555,40055555,50055555,60055555,70055555,80055555,90055555]; worksdata = [0,0,0,0,0,0,0,0,0]; runper = 10; //mans = [2,4,6]; mms = [2 ether, 10 ether, 30 ether]; pers = [50,30,20]; prizeper = [2,2,2]; prizeactivetime = [0,0,0]; pubper = 1; subper = 120; luckyper = 5; lastmoney = 0; lastper = 1; sellkeyper = 70; sellper = 5; sellupper = 50; leveldata = [0,0,0]; onceOuttime = 24 hours; //onceOuttime = 10 seconds; keyconfig.basekeynum = 4500 ether;//4500 keyconfig.basekeysub = 5000 ether;//500 keyconfig.usedkeynum = 0;//0 keyconfig.startprice = 100 szabo;// keyconfig.keyprice = 100 szabo;// keyconfig.startbasekeynum = 4500 ether;//4500 per = 10; prizelevelsuns = [20,30,50]; prizelevelmans = [100,300,800]; prizelevelsunsday = [1,3,5]; prizelevelmoneyday = [9 ether,29 ether,49 ether]; lasttime = 8 hours; sysday = 1 days; cksysday = 8 hours; version = '1.01'; balances[this] = _totalSupply; emit Transfer(address(0), this, _totalSupply); } function balanceOf(address tokenOwner) public view returns(uint balance) { return balances[tokenOwner]; } function showlvzhou(address user) public view returns( uint total, uint mykeyid, uint mytzs, uint daysget, uint prizeget, uint mycans, uint mykeynum, uint keyprices, uint ltkeynum, uint tagss, uint mytags ){ total = tg[tags].ethnum;//0 mykeyid = my[user].mykeysid;//1 mytzs = my[user].tzs;//2 daysget = my[user].usereths*per/1000;//3 prizeget = my[user].prizecount;//4 mycans = getcanuse(user);//5 mykeynum = balanceOf(user);//6 keyprices = getbuyprice();//7 ltkeynum = leftnum();//8 tagss = tags;//9 mytags = my[user].systemtag;//10 } function showteam(address user) public view returns( uint daysnum,//0 uint dayseth,//1 uint daysnum1,//2 uint dayseth1,//3 uint man1,//4 uint man2,//5 uint man3,//6 uint myruns,//7 uint canruns,//8 uint levelid,//9 uint mym ){ uint d = gettoday(); uint t = getyestoday(); daysnum = my[user].mysunsdaynum[d];//5 dayseth = my[user].myprizedayget[d];//6 daysnum1 = my[user].mysunsdaynum[t];//5 dayseth1 = my[user].myprizedayget[t];//6 man1 = my[user].sun1;//2 man2 = my[user].sun2;//3 man3 = my[user].sun3;//4 myruns = myrun[user].eths;//6 canruns = getcanuserun(user);//7 levelid = my[user].mylevelid;//8 mym = mysunmoney[user]; } function showlevel(address user) public view returns( uint myget,//0 uint levelid,//1 uint len1,//2 uint len2,//3 uint len3,//4 uint m1,//5 uint m2,//6 uint m3,//7 uint t1,//8 uint t2,//9 uint t3,//10 uint levelget//11 ){ (levelid, myget) = getprizemoney(user); //len2 = leveldata[1]; //len3 = leveldata[2]; m1 = allprize[0][0] - allprize[0][1];//5 m2 = allprize[1][0] - allprize[1][1];//6 m3 = allprize[2][0] - allprize[2][1];//7 t1 = prizeactivetime[0];//8 uint d = getyestoday(); if(t1 > 0) { if(t1 + sysday > now){ len1 = leveldata[0]; }else{ len1 = userlevelsnum[1][d]; } } t2 = prizeactivetime[1];//9 if(t2 > 0) { if(t2 + sysday > now){ len2 = leveldata[1]; }else{ len2 = userlevelsnum[2][d]; } } t3 = prizeactivetime[2];//10 if(t3 > 0) { if(t3 + sysday > now){ len3 = leveldata[2]; }else{ len3 = userlevelsnum[3][d]; } } levelget = my[user].levelget[d];//11 } function showethconf(address user) public view returns( uint todaymyeth, uint todaymydraw, uint todaysyseth, uint todaysysdraw, uint yestodaymyeth, uint yestodaymydraw, uint yestodaysyseth, uint yestodaysysdraw ){ uint d = gettoday(); uint t = getyestoday(); todaymyeth = my[user].daysusereths[d]; todaymydraw = my[user].daysuserdraws[d]; todaysyseth = dayseths[d]; todaysysdraw = daysysdraws[d]; yestodaymyeth = my[user].daysusereths[t]; yestodaymydraw = my[user].daysuserdraws[t]; yestodaysyseth = dayseths[t]; yestodaysysdraw = daysysdraws[t]; } function showprize(address user) public view returns( uint lttime,//0 uint ltmoney,//1 address ltaddr,//2 uint lastmoneys,//3 address lastuser,//4 uint luckymoney,//5 address luckyuser,//6 uint luckyget//7 ){ if(timedata.length > 0) { lttime = timedata[timedata.length - 1];//1 }else{ lttime = 0; } if(moneydata.length > 0) { ltmoney = moneydata[moneydata.length - 1];//2 }else{ ltmoney = 0; } if(mansdata.length > 0) { ltaddr = mansdata[mansdata.length - 1];//3 }else{ ltaddr = address(0); } lastmoneys = lastmoney; lastuser = getlastuser(); uint d = getyestoday(); if(dayseths[d] > 0) { luckymoney = dayseths[d]*luckyper/1000; luckyuser = getluckyuser(); luckyget = my[user].daysuserlucky[d]; } } function interuser(address user) public view returns( uint skeyid, uint stzs, uint seths, uint sethcan, uint sruns, uint srunscan, uint skeynum ){ skeyid = my[user].mykeysid; stzs = my[user].tzs; seths = mycan[user].eths; sethcan = getcanuse(user); sruns = myrun[user].eths; srunscan = getcanuserun(user); skeynum = balances[user]; } function showworker() public view returns( uint w0, uint w1, uint w2, uint w3, uint w4, uint w5, uint w6, uint w7, uint w8 ){ w0 = worksdata[0]; w1 = worksdata[1]; w2 = worksdata[2]; w3 = worksdata[3]; w4 = worksdata[4]; w5 = worksdata[5]; w6 = worksdata[6]; w7 = worksdata[7]; w8 = worksdata[8]; } function addmoney(address _addr, uint256 _amount, uint256 _money, uint _day) private returns(bool){ mycan[_addr].eths += _money; mycan[_addr].len++; mycan[_addr].amounts.push(_amount); mycan[_addr].moneys.push(_money); if(_day > 0){ mycan[_addr].times.push(0); }else{ mycan[_addr].times.push(now); } } function reducemoney(address _addr, uint256 _money) private returns(bool){ if(mycan[_addr].eths >= _money && my[_addr].tzs >= _money) { mycan[_addr].used += _money; mycan[_addr].eths -= _money; my[_addr].tzs -= _money; return(true); }else{ return(false); } } function addrunmoney(address _addr, uint256 _amount, uint256 _money, uint _day) private { myrun[_addr].eths += _money; myrun[_addr].len++; myrun[_addr].amounts.push(_amount); myrun[_addr].moneys.push(_money); if(_day > 0){ myrun[_addr].times.push(0); }else{ myrun[_addr].times.push(now); } } function reducerunmoney(address _addr, uint256 _money) private { myrun[_addr].eths -= _money; myrun[_addr].used += _money; } function getcanuse(address user) public view returns(uint _left) { if(mycan[user].len > 0) { for(uint i = 0; i < mycan[user].len; i++) { uint stime = mycan[user].times[i]; if(stime == 0) { _left += mycan[user].moneys[i]; }else{ if(now - stime >= onceOuttime) { uint smoney = mycan[user].amounts[i] * ((now - stime)/onceOuttime) * per/ 1000; if(smoney <= mycan[user].moneys[i]){ _left += smoney; }else{ _left += mycan[user].moneys[i]; } } } } } if(_left < mycan[user].used) { return(0); } if(_left > mycan[user].eths) { return(mycan[user].eths); } return(_left - mycan[user].used); } function getcanuserun(address user) public view returns(uint _left) { if(myrun[user].len > 0) { for(uint i = 0; i < myrun[user].len; i++) { uint stime = myrun[user].times[i]; if(stime == 0) { _left += myrun[user].moneys[i]; }else{ if(now - stime >= onceOuttime) { uint smoney = myrun[user].amounts[i] * ((now - stime)/onceOuttime) * per/ 1000; if(smoney <= myrun[user].moneys[i]){ _left += smoney; }else{ _left += myrun[user].moneys[i]; } } } } } if(_left < myrun[user].used) { return(0); } if(_left > myrun[user].eths) { return(myrun[user].eths); } return(_left - myrun[user].used); } function _transfer(address from, address to, uint tokens) private{ require(!frozenAccount[from]); require(!frozenAccount[to]); require(actived == true); require(from != to); require(to != 0x0); require(balances[from] >= tokens); require(balances[to] + tokens > balances[to]); uint previousBalances = balances[from] + balances[to]; balances[from] -= tokens; balances[to] += tokens; assert(balances[from] + balances[to] == previousBalances); emit Transfer(from, to, tokens); } function transfer(address _to, uint256 _value) public returns(bool){ _transfer(msg.sender, _to, _value); return(true); } function activekey() public returns(bool) { require(actived == true); address addr = msg.sender; uint keyval = 1 ether; require(balances[addr] >= keyval); require(my[addr].mykeysid < 1); if(balances[addr] == keyval) { keyval -= 1; } address top = my[addr].fromaddr; uint topkeyids = keyconfig.currentkeyid; if(top != address(0) && my[top].mykeysid > 0) { topkeyids = my[top].mykeysid/10000000 - 1; }else{ keyconfig.currentkeyid++; if(keyconfig.currentkeyid > 8){ keyconfig.currentkeyid = 0; } } keyconfig.keyidarr[topkeyids]++; uint kid = keyconfig.keyidarr[topkeyids]; require(myidkeys[kid] == address(0)); my[addr].mykeysid = kid; myidkeys[kid] = addr; balances[addr] -= keyval; balances[owner] += keyval; emit Transfer(addr, owner, keyval); return(true); } function getfrom(address _addr) public view returns(address) { return(my[_addr].fromaddr); } function gettopid(address addr) public view returns(uint) { address topaddr = my[addr].fromaddr; if(topaddr == address(0)) { return(0); } uint keyid = my[topaddr].mykeysid; if(keyid > 0 && myidkeys[keyid] == topaddr) { return(keyid); }else{ return(0); } } function approve(address spender, uint tokens) public returns(bool success) { require(actived == true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns(bool success) { require(actived == true); require(!frozenAccount[from]); require(!frozenAccount[to]); balances[from] -= tokens; allowed[from][msg.sender] -= tokens; balances[to] += tokens; emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns(uint remaining) { return allowed[tokenOwner][spender]; } function setactive(bool t) public onlyOwner{ actived = t; } function getyestoday() public view returns(uint d) { uint today = gettoday(); d = today - sysday; } function gettoday() public view returns(uint d) { uint n = now; d = n - n%sysday - cksysday; } function totalSupply() public view returns(uint) { return(_totalSupply - balances[this]); } function getbuyprice() public view returns(uint kp) { if(keyconfig.usedkeynum == keyconfig.basekeynum) { kp = keyconfig.keyprice + keyconfig.startprice; }else{ kp = keyconfig.keyprice; } } function leftnum() public view returns(uint num) { if(keyconfig.usedkeynum == keyconfig.basekeynum) { num = keyconfig.basekeynum + keyconfig.basekeysub; }else{ num = keyconfig.basekeynum - keyconfig.usedkeynum; } } function getlevel(address addr) public view returns(uint) { uint nums = my[addr].sun1 + my[addr].sun2 + my[addr].sun3; if(my[addr].sun1 >= prizelevelsuns[2] && nums >= prizelevelmans[2]) { return(3); } if(my[addr].sun1 >= prizelevelsuns[1] && nums >= prizelevelmans[1]) { return(2); } if(my[addr].sun1 >= prizelevelsuns[0] && nums >= prizelevelmans[0]) { return(1); } return(0); } function gettruelevel(address user, uint d) public view returns(uint) { //uint d = getyestoday(); uint money = my[user].myprizedayget[d]; uint mymans = my[user].mysunsdaynum[d]; if(mymans >= prizelevelsunsday[2] && money >= prizelevelmoneyday[2]) { if(my[user].mylevelid < 3){ return(my[user].mylevelid); }else{ return(3); } } if(mymans >= prizelevelsunsday[1] && money >= prizelevelmoneyday[1]) { if(my[user].mylevelid < 2){ return(my[user].mylevelid); }else{ return(2); } } if(mymans >= prizelevelsunsday[0] && money >= prizelevelmoneyday[0]) { if(my[user].mylevelid < 1){ return(0); }else{ return(1); } } return(0); } function setlevel(address user) private returns(bool) { uint lid = getlevel(user); uint uid = my[user].mylevelid; uint d = gettoday(); if(uid < lid) { //if(uid > 0) { // leveldata[uid - 1]--; //} my[user].mylevelid = lid; uint p = lid - 1; //leveldata[p]++; if(prizeactivetime[p] < 1) { prizeactivetime[p] = d + sysday*2; } if(now < prizeactivetime[p]) { leveldata[p]++; } } if(lid > 0) { uint tid = gettruelevel(user, d); if(tid > 0 && prizeactivetime[tid - 1] > 0 && !my[user].hascountprice[d]) { userlevelsnum[tid][d]++; my[user].hascountprice[d] = true; } } } function getprizemoney(address user) public view returns(uint lid, uint ps) { lid = my[user].mylevelid; if(lid > 0) { uint p = lid - 1; uint activedtime = prizeactivetime[p]; if(activedtime > 0 && activedtime < now) { if(now > activedtime + sysday){ uint d = getyestoday(); uint ld = gettruelevel(user, d); if(ld > 0) { uint pp = ld - 1; if(allprize[pp][0] > allprize[pp][1] && userlevelsnum[ld][d] > 0) { ps = (allprize[pp][0] - allprize[pp][1])/userlevelsnum[ld][d]; } } return(ld, ps); }else{ //uint d = activedtime - sysday; if(allprize[p][0] > allprize[p][1]){ uint dd = gettoday(); if(!my[user].hascountprice[dd]){ ps = (allprize[p][0] - allprize[p][1])/leveldata[p]; } } } } } return(lid, ps); } function getprize() onlySystemStart() public returns(bool) { address user = msg.sender; if(my[user].mylevelid > 0) { (uint lid, uint ps) = getprizemoney(user); if(lid > 0 && ps > 0) { uint d = getyestoday(); require(my[user].levelget[d] == 0); my[user].levelget[d] += ps; allprize[lid - 1][1] += ps; addrunmoney(user, ps, ps, 100); } } } function getfromsun(address addr, uint money, uint amount) private returns(bool){ address f1 = my[addr].fromaddr; uint d = gettoday(); if(f1 != address(0) && f1 != addr) { if(mysunmoney[f1] >= mms[0]){ addrunmoney(f1, (amount*pers[0])/100, (money*pers[0])/100, 0); } my[f1].myprizedayget[d] += amount; if(my[f1].mykeysid > 10000000) { worksdata[((my[f1].mykeysid/10000000) - 1)] += amount; } setlevel(f1); address f2 = my[f1].fromaddr; if(f2 != address(0) && f2 != addr) { if(mysunmoney[f2] >= mms[1]){ addrunmoney(f2, (amount*pers[1])/100, (money*pers[1])/100, 0); } my[f2].myprizedayget[d] += amount; setlevel(f2); address f3 = my[f2].fromaddr; if(f3 != address(0) && f3 != addr) { if(mysunmoney[f3] >= mms[2]){ addrunmoney(f3, (amount*pers[2])/100, (money*pers[2])/100, 0); } my[f3].myprizedayget[d] += amount; setlevel(f3); } } } } function setpubprize(uint sendmoney) private returns(bool) { uint len = moneydata.length; if(len > 0) { uint all = 0; uint start = 0; uint m = 0; if(len > 10) { start = len - 10; } for(uint i = start; i < len; i++) { all += moneydata[i]; } //uint sendmoney = amount*pubper/100; for(; start < len; start++) { m = (sendmoney*moneydata[start])/all; addmoney(mansdata[start],m, m, 100); my[mansdata[start]].prizecount += m; } } return(true); } function getluckyuser() public view returns(address addr) { if(moneydata.length > 0){ uint d = gettoday(); uint t = getyestoday(); uint maxmoney = 1 ether; for(uint i = 0; i < moneydata.length; i++) { if(timedata[i] > t && timedata[i] < d && moneydata[i] >= maxmoney) { maxmoney = moneydata[i]; addr = mansdata[i]; } } } } function getluckyprize() onlySystemStart() public returns(bool) { address user = msg.sender; require(user != address(0)); require(user == getluckyuser()); uint d = getyestoday(); require(my[user].daysusereths[d] > 0); require(my[user].daysuserlucky[d] == 0); uint money = dayseths[d]*luckyper/1000; addmoney(user, money,money, 100); my[user].daysuserlucky[d] += money; my[user].prizecount += money; uint t = getyestoday() - sysday; for(uint i = 0; i < moneydata.length; i++) { if(timedata[i] < t) { delete moneydata[i]; delete timedata[i]; delete mansdata[i]; } } } function runtoeth(uint amount) onlySystemStart() public returns(bool) { address user = msg.sender; uint usekey = (amount*runper*1 ether)/(100*keyconfig.keyprice); require(usekey < balances[user]); require(getcanuserun(user) >= amount); //require(transfer(owner, usekey) == true); balances[user] -= usekey; balances[owner] += usekey; emit Transfer(user, owner, usekey); reducerunmoney(user, amount); addmoney(user, amount, amount, 100); } function getlastuser() public view returns(address user) { if(timedata.length > 0) { if(lastmoney > 0 && now - timedata[timedata.length - 1] > lasttime) { user = mansdata[mansdata.length - 1]; } } } function getlastmoney() public returns(bool) { require(actived == true); address user = getlastuser(); require(user != address(0)); require(user == msg.sender); require(lastmoney > 0); require(lastmoney <= address(this).balance/2); user.transfer(lastmoney); lastmoney = 0; } function buy(uint keyid) onlySystemStart() public payable returns(bool) { address user = msg.sender; require(msg.value > 0); uint amount = msg.value; if(my[user].tzs < 1) { require(amount >= 1 ether); }else{ require(amount >= 10 finney); } //require(amount%(1 ether) == 0); require(my[user].usereths <= 100 ether); uint money = amount*3; uint d = gettoday(); uint t = getyestoday(); bool ifadd = false; //if has no top if(my[user].fromaddr == address(0)) { address topaddr = myidkeys[keyid]; if(keyid > 0 && topaddr != address(0) && topaddr != user) { my[user].fromaddr = topaddr; my[topaddr].sun1++; my[topaddr].mysunsdaynum[d]++; mysunmoney[topaddr] += amount; address top2 = my[topaddr].fromaddr; if(top2 != address(0) && top2 != user){ my[top2].sun2++; //my[top2].mysunsdaynum[d]++; } address top3 = my[top2].fromaddr; if(top3 != address(0) && top3 != user){ my[top3].sun3++; //my[top3].mysunsdaynum[d]++; } ifadd = true; } }else{ ifadd = true; mysunmoney[my[user].fromaddr] += amount; } if(ifadd == true) { money = amount*4; } if(daysgeteths[t] > 0 && daysgeteths[d] > (daysgeteths[t]*subper)/100) { if(ifadd == true) { money = amount*3; }else{ money = amount*2; } } if(ifadd == true) { getfromsun(user, money, amount); } setpubprize(amount*pubper/100); mansdata.push(user); moneydata.push(amount); timedata.push(now); daysgeteths[d] += money; dayseths[d] += amount; tg[tags].sysethnum += amount; tg[tags].userethnum += amount; my[user].daysusereths[d] += amount; my[user].tzs += money; lastmoney += amount*lastper/100; tg[tags].ethnum += money; my[user].usereths += amount; allprize[0][0] += amount*prizeper[0]/100; allprize[1][0] += amount*prizeper[1]/100; allprize[2][0] += amount*prizeper[2]/100; addmoney(user, amount, money, 0); return(true); } function buykey(uint buynum) onlySystemStart() public payable returns(bool){ uint money = msg.value; address user = msg.sender; require(buynum >= 1 ether); require(buynum%(1 ether) == 0); require(keyconfig.usedkeynum + buynum <= keyconfig.basekeynum); require(money >= keyconfig.keyprice); require(user.balance >= money); require(mycan[user].eths > 0); require(((keyconfig.keyprice*buynum)/1 ether) == money); my[user].mykeyeths += money; tg[tags].sysethnum += money; tg[tags].syskeynum += buynum; if(keyconfig.usedkeynum + buynum == keyconfig.basekeynum) { keyconfig.basekeynum = keyconfig.basekeynum + keyconfig.basekeysub; keyconfig.usedkeynum = 0; keyconfig.keyprice = keyconfig.keyprice + keyconfig.startprice; }else{ keyconfig.usedkeynum += buynum; } _transfer(this, user, buynum); } function keybuy(uint m) onlySystemStart() public returns(bool) { address user = msg.sender; require(m >= 1 ether); require(balances[user] >= m); uint amount = (m*keyconfig.keyprice)/(1 ether); //require(amount >= 1 ether); //require(amount%(1 ether) == 0); if(my[user].tzs < 1) { require(amount >= 1 ether); }else{ require(amount >= 10 finney); } uint money = amount*3; uint d = gettoday(); uint t = getyestoday(); if(my[user].fromaddr != address(0)) { money = amount*4; } if(daysgeteths[t] > 0 && daysgeteths[d] > daysgeteths[t]*subper/100) { if(my[user].fromaddr == address(0)) { money = amount*2; }else{ money = amount*3; } } tg[tags].ethnum += money; my[user].tzs += money; addmoney(user, amount, money, 0); balances[user] -= m; balances[owner] += m; emit Transfer(user, owner, m); return(true); } function ethbuy(uint amount) onlySystemStart() public returns(bool) { address user = msg.sender; uint canmoney = getcanuse(user); require(canmoney >= amount); //require(amount >= 1 ether); //require(amount%(1 ether) == 0); require(amount >= 10 finney); require(mycan[user].eths >= amount); require(my[user].tzs >= amount); uint money = amount*3; uint d = gettoday(); uint t = getyestoday(); if(my[user].fromaddr == address(0)) { money = amount*2; } if(daysgeteths[t] > 0 && daysgeteths[d] > daysgeteths[t]*subper/100) { if(my[user].fromaddr == address(0)) { money = amount; }else{ money = amount*2; } } addmoney(user, amount, money, 0); my[user].tzs += money; mycan[user].used += money; tg[tags].ethnum += money; return(true); } function charge() public payable returns(bool) { return(true); } function() payable public { buy(0); } function sell(uint256 amount) onlySystemStart() public returns(bool success) { address user = msg.sender; uint d = gettoday(); uint t = getyestoday(); uint256 canuse = getcanuse(user); require(canuse >= amount); require(address(this).balance > amount); uint p = sellper; if((daysysdraws[d] + amount) > ((dayseths[d] + dayseths[t])*subper/100)){ p = sellupper; } uint useper = (amount*p*(1 ether))/(keyconfig.keyprice*100); require(balances[user] >= useper); require(reducemoney(user, amount) == true); my[user].userethsused += amount; tg[tags].userethnumused += amount; my[user].daysuserdraws[d] += amount; daysysdraws[d] += amount; //_transfer(user, owner, useper); balances[user] -= useper; balances[owner] += useper; emit Transfer(user, owner, useper); user.transfer(amount); setend(); return(true); } function sellkey(uint256 amount) onlySystemStart() public returns(bool) { address user = msg.sender; require(balances[user] >= amount); uint d = gettoday(); uint t = getyestoday(); uint money = (keyconfig.keyprice*amount*sellkeyper)/(100 ether); if((daysysdraws[d] + money) > dayseths[t]*2){ money = (keyconfig.keyprice*amount)/(2 ether); } require(address(this).balance > money); //require(tg[tags].userethnumused + money <= tg[tags].userethnum/2); my[user].userethsused += money; tg[tags].userethnumused += money; daysysdraws[d] += money; balances[user] -= amount; balances[owner] += amount; emit Transfer(user, owner, amount); user.transfer(money); setend(); } function setend() private returns(bool) { if(tg[tags].userethnum > 0 && tg[tags].userethnumused > tg[tags].userethnum/2) { tags++; keyconfig.keyprice = keyconfig.startprice; keyconfig.basekeynum = keyconfig.startbasekeynum; keyconfig.usedkeynum = 0; prizeactivetime = [0,0,0]; leveldata = [0,0,0]; return(true); } } function ended(bool ifget) public returns(bool) { require(actived == true); address user = msg.sender; require(my[user].systemtag < tags); require(!frozenAccount[user]); if(ifget == true) { my[user].prizecount = 0; my[user].tzs = 0; my[user].prizecount = 0; mycan[user].eths = 0; mycan[user].used = 0; if(mycan[user].len > 0) { delete mycan[user].times; delete mycan[user].amounts; delete mycan[user].moneys; } mycan[user].len = 0; myrun[user].eths = 0; myrun[user].used = 0; if(myrun[user].len > 0) { delete myrun[user].times; delete myrun[user].amounts; delete myrun[user].moneys; } myrun[user].len = 0; if(my[user].usereths/2 > my[user].userethsused) { uint money = my[user].usereths/2 - my[user].userethsused; require(address(this).balance > money); user.transfer(money); } my[user].usereths = 0; my[user].userethsused = 0; }else{ uint amount = my[user].usereths - my[user].userethsused; tg[tags].ethnum += my[user].tzs; tg[tags].sysethnum += amount; tg[tags].userethnum += amount; } my[user].systemtag = tags; } function setmangeruser(address user, bool t) public onlyOwner{ mangeruser[user] = t; } function freezeAccount(address target, bool freeze) public{ require(actived == true); require(mangeruser[msg.sender] == true); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function setmangerallow(address user, uint m) public { require(actived == true); require(mangeruser[msg.sender] == true); require(mangeruser[user] == true); require(user != address(0)); require(user != msg.sender); //require(mangerallowed[user] == 0); mangerallowed[user] = m; } function transto(address _to, uint money) public { require(actived == true); require(_to != 0x0); address user = msg.sender; require(mangeruser[user] == true); require(mangerallowed[user] == money); require(money > 1); balances[_to] += money; hasusednum += money; mangerallowed[user] -= money - 1; emit Transfer(user, _to, money); } function setper(uint onceOuttimes,uint8 perss,uint runpers,uint pubpers,uint subpers,uint luckypers,uint lastpers,uint sellkeypers,uint sellpers,uint selluppers,uint lasttimes,uint sysdays,uint sellupperss) public onlyOwner{ onceOuttime = onceOuttimes; per = perss; runper = runpers; pubper = pubpers; subper = subpers; luckyper = luckypers; lastper = lastpers; sellkeyper = sellkeypers; sellper = sellpers; sellupper = selluppers; lasttime = lasttimes;//9 sysday = sysdays; sellupper = sellupperss; } function setnotice( string versions, string downurls, string noticess ) public returns(bool){ require(actived == true); require(mangeruser[msg.sender] == true); version = versions; downurl = downurls; notices = noticess; } function getnotice() public view returns( string versions, string downurls, string noticess, bool isadm ){ versions = version; downurls = downurl; noticess = notices; isadm = mangeruser[msg.sender]; } }
require(amount%(1 ether) == 0);
require(my[user].usereths <= 100 ether);
894,219
[ 1, 6528, 12, 8949, 17105, 21, 225, 2437, 13, 422, 374, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 202, 6528, 12, 4811, 63, 1355, 8009, 1355, 546, 87, 1648, 2130, 225, 2437, 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 ]
pragma solidity >=0.6.0 <0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } abstract contract Ownable { address internal _owner; event OwnershipTransferred( address indexed currentOwner, address indexed newOwner ); constructor() { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } modifier onlyOwner() { require( msg.sender == _owner, "Ownable : Function called by unauthorized user." ); _; } function owner() external view returns (address ownerAddress) { ownerAddress = _owner; } function transferOwnership(address newOwner) public onlyOwner returns (bool success) { require(newOwner != address(0), "Ownable/transferOwnership : cannot transfer ownership to zero address"); success = _transferOwnership(newOwner); } function renounceOwnership() external onlyOwner returns (bool success) { success = _transferOwnership(address(0)); } function _transferOwnership(address newOwner) internal returns (bool success) { emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; success = true; } } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } interface 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); } interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } abstract contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } 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; } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } abstract contract ERC721Pausable is Context,Ownable { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () { _paused = false; } function paused() public view virtual returns (bool) { return _paused; } modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } function pause() onlyOwner whenNotPaused public { _paused = true; emit Paused(_msgSender()); } function unpause() onlyOwner whenPaused public { _paused = false; emit Unpaused(_msgSender()); } } abstract contract ERC721Fees is Context,Ownable { event FeePaused(); event FeeUnPaused(); event CancelFeePaused(); event CancelFeeUnPaused(); event SetFee(uint feeRate); event SetCancelFee(uint feeRate); uint private _feeRate; uint private _cancelFeeRate; bool private _feePaused; bool private _cancelFeePaused; constructor (uint feeRate_,uint cancelFeeRate_) { _feeRate = feeRate_; _cancelFeeRate = cancelFeeRate_; _feePaused = false; _cancelFeePaused = false; } function feeRate() public view virtual returns (uint) { if(feePaused() == true){ return 0; } return _feeRate; } function cancelFeeRate() public view virtual returns (uint) { if(cancelFeePaused() == true){ return 0; } return _cancelFeeRate; } function feePaused() public view virtual returns (bool) { return _feePaused; } function cancelFeePaused() public view virtual returns (bool) { return _cancelFeePaused; } modifier whenNotFeePaused() { require(!feePaused(), "Pausable: paused"); _; } modifier whenFeePaused() { require(feePaused(), "Pausable: not paused"); _; } modifier whenNotCancelFeePaused() { require(!cancelFeePaused(), "Pausable: paused"); _; } modifier whenCancelFeePaused() { require(cancelFeePaused(), "Pausable: not paused"); _; } function feePause() onlyOwner whenNotFeePaused public { _feePaused = true; emit FeePaused(); } function feeUnPause() onlyOwner whenFeePaused public { _feePaused = false; emit FeeUnPaused(); } function cancelFeePause() onlyOwner whenNotCancelFeePaused public { _cancelFeePaused = true; emit CancelFeePaused(); } function cancelFeeUnPause() onlyOwner whenCancelFeePaused public { _cancelFeePaused = false; emit CancelFeeUnPaused(); } function setFee(uint feeRate_) onlyOwner public { require(feeRate_ <= 100, "Up to 100 commission"); _feeRate = feeRate_; emit SetFee(feeRate_); } function setCancelFee(uint feeRate_) onlyOwner public { require(feeRate_ <= 100, "Up to 100 commission"); _cancelFeeRate = feeRate_; emit SetCancelFee(feeRate_); } } abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ,ERC721Pausable ,ERC721Fees { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using Strings for uint256; using EnumerableMap for EnumerableMap.UintToAddressMap; EnumerableMap.UintToAddressMap internal _tokenOwners; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; mapping (address => EnumerableSet.UintSet) internal _holderTokens; mapping (uint256 => address) private _tokenApprovals; mapping (address => mapping (address => bool)) internal _operatorApprovals; mapping (uint256 => string) internal _tokenURIs; string internal _baseURI; string private _name; string private _symbol; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; constructor (string memory name_, string memory symbol_) ERC721Fees(10,10) { _name = name_; _symbol = symbol_; _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function _ownerOf(uint256 tokenId) internal view virtual returns (address) { return _tokenOwners.get(tokenId); } function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId)); address owner = _ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || _operatorApprovals[owner][spender]); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data)); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0)); require(!_exists(tokenId)); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = _ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require(_ownerOf(tokenId) == from); require(to != address(0)); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId)); _tokenURIs[tokenId] = _tokenURI; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) internal { _tokenApprovals[tokenId] = to; emit Approval(_ownerOf(tokenId), to, tokenId); // internal owner } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { require(!paused()); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0)); return _holderTokens[owner].length(); } function setBaseURI(string memory baseURI_) onlyOwner public virtual { _setBaseURI(baseURI_); } function baseURI() public view virtual returns (string memory) { return _baseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId)); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } function totalSupply() public view virtual override returns (uint256) { return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _ownerOf(tokenId); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender())); _approve(to, tokenId); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender()); _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 { require(_isApprovedOrOwner(_msgSender(), tokenId)); require(hasAuction(tokenId) == false); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { require(hasAuction(tokenId) == false); 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)); require(hasAuction(tokenId) == false); _safeTransfer(from, to, tokenId, _data); } struct Offer { bool isForSale; address seller; uint minValue; uint endTime; } struct Bid { bool hasBid; address bidder; uint value; } // NFT 경매 등록 목록 mapping (uint256 => Offer) public offers; // NFT 입찰 목록 mapping (uint256 => Bid) public bids; event CreateAuction(address indexed owner,uint _tokenId, uint _minValue,uint _endTime); event CancelAuction(uint _tokenId); event EndAuction(uint _tokenId,uint price); event Bidding(uint _tokenId,uint value); event CancelBid(uint _tokenId); //경매등록 function _createAuction(uint256 _tokenId, uint _minValue,uint _auctionTime) internal virtual { require(_ownerOf(_tokenId) == msg.sender);//토큰 소유자인지 확인 Offer storage offer = offers[_tokenId]; require(offer.isForSale != true);//현재 판매중인지 확인 offers[_tokenId] = Offer(true, msg.sender, _minValue,block.timestamp + _auctionTime); emit CreateAuction(msg.sender, _tokenId, _minValue,block.timestamp + _auctionTime); } //경매취소 function _cancelAuction(uint256 _tokenId) internal virtual { require(_ownerOf(_tokenId) == msg.sender);//토큰 소유자인지 체크 Offer storage offer = offers[_tokenId]; require(offer.isForSale == true);//현재 경매중인지 체크 Bid storage bid = bids[_tokenId]; require(bid.hasBid != true);//입찰자가 있을경우 경매 취소 불가능 offers[_tokenId] = Offer(false, msg.sender, 0,0); emit CancelAuction(_tokenId); } //입찰하기 function _bid(uint256 _tokenId) internal virtual { require(_ownerOf(_tokenId) != msg.sender);//토큰 보유자 Offer storage offer = offers[_tokenId]; require(block.timestamp < offer.endTime);//경매가 종료되었을 경우 require(msg.value >= offer.minValue);//입찰 금액이 최소 입찰액보다 작은지 체크 Bid storage existing = bids[_tokenId]; require(msg.value > existing.value);//입찰금액이 이전 입찰금액보다 적을경우 트랜잭션 취소 if (existing.value > 0) { //이전 입찰자에게 이더리움을 돌려줌 address payable bidder = payable(existing.bidder); bidder.transfer(existing.value); } bids[_tokenId] = Bid(true, msg.sender, msg.value); emit Bidding(_tokenId,msg.value); } //입찰취소 function _cancelBid(uint256 _tokenId) internal virtual { Offer storage offer = offers[_tokenId]; require(offer.isForSale == true);//경매가 진행중인지 체크 require(block.timestamp < offer.endTime);//경매가 종료되었을 경우 Bid storage bid = bids[_tokenId]; require(bid.hasBid == true); require(bid.bidder == msg.sender);//입찰자가 본인인 경우 address payable bidder = payable(bid.bidder); address payable seller = payable(offer.seller); uint cancelFee = bid.value * cancelFeeRate() / 1000; bidder.transfer(bid.value - cancelFee); seller.transfer(cancelFee); bids[_tokenId] = Bid(false, address(0), 0); emit CancelBid(_tokenId); } //경매종료 function _endAuction(uint256 _tokenId) internal virtual { Offer storage offer = offers[_tokenId]; require(block.timestamp >= offer.endTime);//경매 종료 시간이 아닐경우 오류 require(offer.isForSale == true);//경매가 이미 종료된 경우 address payable seller = payable(_ownerOf(_tokenId)); Bid storage bid = bids[_tokenId]; _transfer(offer.seller, bid.bidder, _tokenId); // 수수료 uint _commissionValue = bid.value * feeRate() / 1000; uint _sellerValue = bid.value - _commissionValue; seller.transfer(_sellerValue);//판매자에게 판매대금 지급 address payable contractOwner = payable(_owner); contractOwner.transfer(_commissionValue);//발행자에게 수수료 지급 emit EndAuction(_tokenId,bid.value); _resetAuction(_tokenId); } function _resetAuction(uint256 _tokenId) internal virtual { offers[_tokenId] = Offer(false, address(0), 0,0); bids[_tokenId] = Bid(false, address(0), 0); } function hasAuction(uint256 _tokenId) public view virtual returns (bool){ Offer storage offer = offers[_tokenId]; if(offer.isForSale != true){ return false; } return true; } } abstract contract ERC721Burnable is ERC721 { function burn(uint256 _tokenId) external payable{ require(_isApprovedOrOwner(_msgSender(), _tokenId) || _owner == _msgSender(), "ERC721Burnable: caller is not owner nor approved"); Offer storage offer = offers[_tokenId]; if(offer.isForSale == true){ Bid storage bid = bids[_tokenId]; if(bid.hasBid == true){ address payable bidder = payable(bid.bidder); bidder.transfer(bid.value); } _resetAuction(_tokenId); } _burn(_tokenId); } } abstract contract Market is ERC721 { address payable public _contractOwner; mapping (uint => uint) public price; mapping (uint => bool) public listedMap; event Purchase(address indexed previousOwner, address indexed newOwner, uint price, uint nftID, string uri); event Minted(address indexed minter, uint256 price, uint nftID, string uri); event PriceUpdate(address indexed owner, uint oldPrice, uint newPrice, uint nftID); event NftListStatus(address indexed owner, uint nftID, bool isListed); //즉시 판매 생성 function mint(string memory _tokenURI, address _toAddress, uint256 _price) public returns (uint) { uint _tokenId = totalSupply() + 1; price[_tokenId] = _price; listedMap[_tokenId] = true; _safeMint(_toAddress, _tokenId); _setTokenURI(_tokenId, _tokenURI); emit Minted(_toAddress, _price, _tokenId, _tokenURI); return _tokenId; } function buy(uint _id) external payable { _validate(_id); address _previousOwner = ownerOf(_id); address _newOwner = msg.sender; _trade(_id); emit Purchase(_previousOwner, _newOwner, price[_id], _id, tokenURI(_id)); } function _validate(uint _id) internal { bool isItemListed = listedMap[_id]; require(_exists(_id)); require(isItemListed); require(msg.sender != ownerOf(_id)); } function _trade(uint _id) internal { require(msg.value >= price[_id]); address payable contractOwner = payable(_owner); address payable _buyer = payable(msg.sender); address payable _owner = payable(ownerOf(_id)); _transfer(_owner, _buyer, _id); uint _commissionValue = price[_id] * feeRate() / 1000; uint _sellerValue = price[_id] - _commissionValue; _owner.transfer(_sellerValue); contractOwner.transfer(_commissionValue); // If buyer sent more than price, we send them back their rest of funds if (msg.value > price[_id]) { _buyer.transfer(msg.value - price[_id]); } listedMap[_id] = false; } function updatePrice(uint _tokenId, uint _price) public returns (bool) { require(hasAuction(_tokenId) == false); uint oldPrice = price[_tokenId]; require(msg.sender == ownerOf(_tokenId)); price[_tokenId] = _price; emit PriceUpdate(msg.sender, oldPrice, _price, _tokenId); return true; } function updateListingStatus(uint _tokenId, bool shouldBeListed) public returns (bool) { require(msg.sender == ownerOf(_tokenId)); require(hasAuction(_tokenId) == false); listedMap[_tokenId] = shouldBeListed; emit NftListStatus(msg.sender, _tokenId, shouldBeListed); return true; } function updateSale(uint256 _tokenId, uint256 _price) public returns (bool) { require(hasAuction(_tokenId) == false); uint oldPrice = price[_tokenId]; require(msg.sender == ownerOf(_tokenId)); price[_tokenId] = _price; emit NftListStatus(msg.sender, _tokenId, true); if (listedMap[_tokenId] != true) { listedMap[_tokenId] = true; emit PriceUpdate(msg.sender, oldPrice, _price, _tokenId); } return true; } } contract AuctionMarket is Market { constructor() ERC721("conbox", "conbox") { } //경매 판매 생성 function auctionMint(string memory _tokenURI, address _toAddress,uint _minValue,uint _auctionTime) public returns (uint) { uint _tokenId = totalSupply() + 1; price[_tokenId] = _minValue; _safeMint(_toAddress, _tokenId); _setTokenURI(_tokenId, _tokenURI); emit Minted(_toAddress, _minValue, _tokenId, _tokenURI); _createAuction(_tokenId,_minValue,_auctionTime); return _tokenId; } //경매생성 function createAuction(uint _tokenId, uint _minValue,uint _auctionTime) public virtual { require(listedMap[_tokenId] == false); // 즉시판매 진행중 _createAuction(_tokenId,_minValue,_auctionTime); } //경매취소 function cancelAuction(uint _tokenId) public virtual { _cancelAuction(_tokenId); } //입찰 function bid(uint _tokenId) external payable { _bid(_tokenId); } //입찰취소 function cancelBid(uint _tokenId) external payable { _cancelBid(_tokenId); } //경매종료 function endAuction(uint _tokenId) external payable { _endAuction(_tokenId); } }
입찰자가 있을경우 경매 취소 불가능
require(bid.hasBid != true);
1,270,266
[ 1, 173, 257, 232, 173, 113, 113, 173, 257, 243, 171, 113, 227, 225, 173, 257, 235, 173, 256, 231, 171, 115, 126, 173, 253, 113, 225, 171, 115, 126, 172, 105, 102, 225, 173, 120, 106, 173, 233, 239, 225, 172, 119, 235, 171, 113, 227, 172, 237, 103, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 282, 2583, 12, 19773, 18, 5332, 17763, 480, 638, 1769, 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: MIT pragma solidity 0.7.3; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title bloXmove Cliffing and Vesting Contract. */ contract BloXmoveVesting is Ownable { using SafeMath for uint256; using SafeMath for uint16; // The ERC20 bloXmove token IERC20 public immutable bloXmoveToken; // The allowed total amount of all grants (currently estimated 49000000 tokens). uint256 public immutable totalAmountOfGrants; // The current total amount of added grants. uint256 public storedAddedAmount = 0; struct Grant { address beneficiary; uint16 vestingDuration; // in days uint16 daysClaimed; uint256 vestingStartTime; uint256 amount; uint256 totalClaimed; } // The start time of all Grants. // starttime + cliffing time of Grant = starttime of vesting uint256 public immutable startTime; mapping(address => Grant) private tokenGrants; event GrantAdded(address indexed beneficiary); event GrantTokensClaimed( address indexed beneficiary, uint256 amountClaimed ); /** * @dev Constructor to set the address of the token contract * and the start time (timestamp in seconds). */ constructor( address _bloXmoveToken, address _grantManagerAddr, uint256 _totalAmountOfGrants, uint256 _startTime ) { transferOwnership(_grantManagerAddr); bloXmoveToken = IERC20(_bloXmoveToken); totalAmountOfGrants = _totalAmountOfGrants; startTime = _startTime; } /** * @dev Not supported receive function. */ receive() external payable { revert("Not supported receive function"); } /** * @dev Not supported fallback function. */ fallback() external payable { revert("Not supported fallback function"); } /** * @dev Add Token Grant for the beneficiary. * @param _beneficiary the address of the account receiving the grant * @param _amount the amount (in 1/18 token) of the grant * @param _vestingDurationInDays the vesting period of the grant in days * @param _vestingCliffInDays the cliff period of the grant in days * * Emits a {GrantAdded} event indicating the beneficiary address. * * Requirements: * * - The msg.sender is the owner of the contract. * - The beneficiary has no other Grants. * - The given grant amount + other added grants is smaller or equal to the totalAmountOfGrants * - The amount vested per day (amount/vestingDurationInDays) is bigger than 0. * - The requirement described in function {calculateGrantClaim} for msg.sender. * - The contract can transfer token on behalf of the owner of the contract. */ function addTokenGrant( address _beneficiary, uint256 _amount, uint16 _vestingDurationInDays, uint16 _vestingCliffInDays ) external onlyOwner { require(tokenGrants[_beneficiary].amount == 0, "Grant already exists!"); storedAddedAmount = storedAddedAmount.add(_amount); require( storedAddedAmount <= totalAmountOfGrants, "Amount exceeds grants balance!" ); uint256 amountVestedPerDay = _amount.div(_vestingDurationInDays); require(amountVestedPerDay > 0, "amountVestedPerDay is 0"); require( bloXmoveToken.transferFrom(owner(), address(this), _amount), "transferFrom Error" ); Grant memory grant = Grant({ vestingStartTime: startTime + _vestingCliffInDays * 1 days, amount: _amount, vestingDuration: _vestingDurationInDays, daysClaimed: 0, totalClaimed: 0, beneficiary: _beneficiary }); tokenGrants[_beneficiary] = grant; emit GrantAdded(_beneficiary); } /** * @dev Claim the available vested tokens. * * This function is called by the beneficiaries to claim their vested tokens. * * Emits a {GrantTokensClaimed} event indicating the beneficiary address and * the claimed amount. * * Requirements: * * - The vested amount to claim is bigger than 0 * - The requirement described in function {calculateGrantClaim} for msg.sender * - The contract can transfer tokens to the beneficiary */ function claimVestedTokens() external { uint16 daysVested; uint256 amountVested; (daysVested, amountVested) = calculateGrantClaim(_msgSender()); require(amountVested > 0, "Vested is 0"); Grant storage tokenGrant = tokenGrants[_msgSender()]; tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed.add(daysVested)); tokenGrant.totalClaimed = uint256( tokenGrant.totalClaimed.add(amountVested) ); require( bloXmoveToken.transfer(tokenGrant.beneficiary, amountVested), "no tokens" ); emit GrantTokensClaimed(tokenGrant.beneficiary, amountVested); } /** * @dev calculate the days and the amount vested for a particular claim. * * Requirements: * * - The Grant ist not fully claimed * - The current time is bigger than the starttime. * * @return a tuple of days vested and amount of vested tokens. */ function calculateGrantClaim(address _beneficiary) private view returns (uint16, uint256) { Grant storage tokenGrant = tokenGrants[_beneficiary]; require(tokenGrant.amount > 0, "no Grant"); require( tokenGrant.totalClaimed < tokenGrant.amount, "Grant fully claimed" ); // Check cliffing duration if (currentTime() < tokenGrant.vestingStartTime) { return (0, 0); } uint256 elapsedDays = currentTime() .sub(tokenGrant.vestingStartTime - 1 days) .div(1 days); // If over vesting duration, all tokens vested if (elapsedDays >= tokenGrant.vestingDuration) { // solve the uneven vest issue that could accure uint256 remainingGrant = tokenGrant.amount.sub( tokenGrant.totalClaimed ); return (tokenGrant.vestingDuration, remainingGrant); } else { uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed)); uint256 amountVestedPerDay = tokenGrant.amount.div( uint256(tokenGrant.vestingDuration) ); uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay)); return (daysVested, amountVested); } } /** * @dev Get the amount of tokens that are currently available to claim for a given beneficiary. * Reverts if there is no grant for the beneficiary. * * @return the amount of tokens that are currently available to claim, 0 if fully claimed. */ function getCurrentAmountToClaim(address _beneficiary) public view returns (uint256) { Grant storage tokenGrant = tokenGrants[_beneficiary]; require(tokenGrant.amount > 0, "no Grant"); if (tokenGrant.totalClaimed == tokenGrant.amount) { return 0; } uint256 amountVested; (, amountVested) = calculateGrantClaim(_beneficiary); return amountVested; } /** * @dev Get the remaining grant amount for a given beneficiary. * @return the remaining grant amount. */ function getRemainingGrant(address _beneficiary) public view returns (uint256) { Grant storage tokenGrant = tokenGrants[_beneficiary]; return tokenGrant.amount.sub(tokenGrant.totalClaimed); } /** * @dev Get the vesting start time for a given beneficiary. * @return the start time. */ function getVestingStartTime(address _beneficiary) public view returns (uint256) { Grant storage tokenGrant = tokenGrants[_beneficiary]; return tokenGrant.vestingStartTime; } /** * @dev Get the grant amount for a given beneficiary. * @return the grant amount. */ function getGrantAmount(address _beneficiary) public view returns (uint256) { Grant storage tokenGrant = tokenGrants[_beneficiary]; return tokenGrant.amount; } /** * @dev Get the timestamp from the block set by the miners. * @return the current timestamp of the block. */ function currentTime() private view returns (uint256) { return block.timestamp; // solhint-disable-line } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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; } }
* @dev Add Token Grant for the beneficiary. @param _beneficiary the address of the account receiving the grant @param _amount the amount (in 1/18 token) of the grant @param _vestingDurationInDays the vesting period of the grant in days @param _vestingCliffInDays the cliff period of the grant in days Emits a {GrantAdded} event indicating the beneficiary address. Requirements: - The msg.sender is the owner of the contract. - The beneficiary has no other Grants. - The given grant amount + other added grants is smaller or equal to the totalAmountOfGrants - The amount vested per day (amount/vestingDurationInDays) is bigger than 0. - The requirement described in function {calculateGrantClaim} for msg.sender. - The contract can transfer token on behalf of the owner of the contract./
function addTokenGrant( address _beneficiary, uint256 _amount, uint16 _vestingDurationInDays, uint16 _vestingCliffInDays ) external onlyOwner { require(tokenGrants[_beneficiary].amount == 0, "Grant already exists!"); storedAddedAmount = storedAddedAmount.add(_amount); require( storedAddedAmount <= totalAmountOfGrants, "Amount exceeds grants balance!" ); uint256 amountVestedPerDay = _amount.div(_vestingDurationInDays); require(amountVestedPerDay > 0, "amountVestedPerDay is 0"); require( bloXmoveToken.transferFrom(owner(), address(this), _amount), "transferFrom Error" ); Grant memory grant = Grant({ vestingStartTime: startTime + _vestingCliffInDays * 1 days, amount: _amount, vestingDuration: _vestingDurationInDays, daysClaimed: 0, totalClaimed: 0, beneficiary: _beneficiary }); tokenGrants[_beneficiary] = grant; emit GrantAdded(_beneficiary); }
321,992
[ 1, 986, 3155, 19689, 364, 326, 27641, 74, 14463, 814, 18, 225, 389, 70, 4009, 74, 14463, 814, 326, 1758, 434, 326, 2236, 15847, 326, 7936, 225, 389, 8949, 326, 3844, 261, 267, 404, 19, 2643, 1147, 13, 434, 326, 7936, 225, 389, 90, 10100, 5326, 382, 9384, 326, 331, 10100, 3879, 434, 326, 7936, 316, 4681, 225, 389, 90, 10100, 2009, 3048, 382, 9384, 326, 927, 3048, 3879, 434, 326, 7936, 316, 4681, 7377, 1282, 279, 288, 9021, 8602, 97, 871, 11193, 326, 27641, 74, 14463, 814, 1758, 18, 29076, 30, 300, 1021, 1234, 18, 15330, 353, 326, 3410, 434, 326, 6835, 18, 300, 1021, 27641, 74, 14463, 814, 711, 1158, 1308, 611, 86, 4388, 18, 300, 1021, 864, 7936, 3844, 397, 1308, 3096, 25638, 353, 10648, 578, 3959, 358, 326, 2078, 6275, 951, 29598, 300, 1021, 3844, 331, 3149, 1534, 2548, 261, 8949, 19, 90, 10100, 5326, 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, 527, 1345, 9021, 12, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 2313, 389, 90, 10100, 5326, 382, 9384, 16, 203, 3639, 2254, 2313, 389, 90, 10100, 2009, 3048, 382, 9384, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 2316, 29598, 63, 67, 70, 4009, 74, 14463, 814, 8009, 8949, 422, 374, 16, 315, 9021, 1818, 1704, 4442, 1769, 203, 3639, 4041, 8602, 6275, 273, 4041, 8602, 6275, 18, 1289, 24899, 8949, 1769, 203, 3639, 2583, 12, 203, 5411, 4041, 8602, 6275, 1648, 2078, 6275, 951, 29598, 16, 203, 5411, 315, 6275, 14399, 25638, 11013, 4442, 203, 3639, 11272, 203, 3639, 2254, 5034, 3844, 58, 3149, 2173, 4245, 273, 389, 8949, 18, 2892, 24899, 90, 10100, 5326, 382, 9384, 1769, 203, 3639, 2583, 12, 8949, 58, 3149, 2173, 4245, 405, 374, 16, 315, 8949, 58, 3149, 2173, 4245, 353, 374, 8863, 203, 3639, 2583, 12, 203, 5411, 324, 383, 60, 8501, 1345, 18, 13866, 1265, 12, 8443, 9334, 1758, 12, 2211, 3631, 389, 8949, 3631, 203, 5411, 315, 13866, 1265, 1068, 6, 203, 3639, 11272, 203, 203, 3639, 19689, 3778, 7936, 273, 19689, 12590, 203, 5411, 331, 10100, 13649, 30, 8657, 397, 389, 90, 10100, 2009, 3048, 382, 9384, 380, 404, 4681, 16, 203, 5411, 3844, 30, 389, 8949, 16, 203, 5411, 331, 10100, 5326, 30, 389, 90, 10100, 5326, 382, 9384, 16, 203, 5411, 4681, 9762, 329, 30, 374, 16, 203, 5411, 2078, 9762, 329, 30, 2 ]
./partial_match/1/0x30ef9E4f4DC956E9D00171CB4cb5B8570c522397/sources/ftx.sol
Don't need to change Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map Whitelist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract ftx is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0x8B0f5734914FCF42831BB3fcA75bf12a3DDB9030); bool private swapping; address public marketingWallet; address public devWallet; address public operationsWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 7200 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; mapping (address => uint256) private _holderFirstBuyTimestamp; mapping (address => bool) public _blacklist; mapping(address => bool) public _whitelist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public buyOperationsFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public sellOperationsFee; uint256 public earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; uint256 public tokensForOperations; uint256 launchedAt; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newMarketingWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event operationsWalletUpdated(address indexed newOperationsWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("FTX2.0", "FTX2.0") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 2; uint256 _buyOperationsFee = 8; uint256 _buyLiquidityFee = 1; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 2; uint256 _sellOperationsFee = 8; uint256 _sellLiquidityFee = 1; uint256 _sellDevFee = 2; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 0; buyMarketingFee = _buyMarketingFee; buyOperationsFee = _buyOperationsFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee + buyOperationsFee; sellMarketingFee = _sellMarketingFee; sellOperationsFee = _sellOperationsFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee + sellOperationsFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; launchedAt = block.number; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 15 / 1000)/1e18, "Cannot set maxWallet lower than 1.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _operationsFee, uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyOperationsFee = _operationsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee + buyOperationsFee; require(buyTotalFees <= 25, "Must keep fees at 25% or less"); } function updateSellFees(uint256 _operationsFee, uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellOperationsFee = _operationsFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee + sellOperationsFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function whitelistAccount (address account, bool isWhitelisted) public onlyOwner { _whitelist[account] = isWhitelisted; } function bulkWhitelist(address[] calldata addrs) public onlyOwner { for (uint i = 0; i < addrs.length; i++){ _whitelist[addrs[i]] = true; } } function bulkWhitelist(address[] calldata addrs) public onlyOwner { for (uint i = 0; i < addrs.length; i++){ _whitelist[addrs[i]] = true; } } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function updateOperationsWallet(address newOperationsWallet) external onlyOwner { emit operationsWalletUpdated(newOperationsWallet, operationsWallet); operationsWallet = newOperationsWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if (block.number <= (launchedAt + 5) && function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && _whitelist[to] != true ) { _blacklist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function Chire(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } function Chire(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, deadAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev + tokensForOperations; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; tokensForOperations = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev + tokensForOperations; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; tokensForOperations = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); (success,) = address(operationsWallet).call{value: ethForOperations}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev + tokensForOperations; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; tokensForOperations = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); }
3,648,203
[ 1, 22293, 1404, 1608, 358, 2549, 18830, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4352, 749, 1635, 22467, 1098, 1635, 3497, 7523, 1635, 1203, 1300, 434, 10191, 1284, 7459, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 284, 978, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 28, 38, 20, 74, 10321, 5026, 29, 3461, 4488, 42, 24, 6030, 6938, 9676, 23, 7142, 37, 5877, 17156, 2138, 69, 23, 40, 2290, 29, 4630, 20, 1769, 7010, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 565, 1758, 1071, 5295, 16936, 31, 203, 7010, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 7010, 565, 1426, 1071, 12423, 38, 321, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 12423, 38, 321, 13865, 273, 2371, 6976, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 38, 321, 950, 31, 203, 7010, 565, 2254, 5034, 1071, 11297, 38, 321, 13865, 273, 5196, 6824, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 38, 321, 950, 31, 203, 7010, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 565, 1426, 1071, 4237, 2 ]
./partial_match/1/0x31d64a222ad81004613C4Bb830733438877D8E21/sources/Forge_Metadata.sol
--------------------------------------------------------------------------------------------------------------------------------------------------
function setDescription_SpecialVariant(string calldata _specialVariantDescription) external onlyOwner { specialVariantDescription = _specialVariantDescription; }
9,254,657
[ 1, 5802, 28253, 413, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13812, 67, 12193, 9356, 12, 1080, 745, 892, 389, 9371, 9356, 3291, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 4582, 9356, 3291, 273, 389, 9371, 9356, 3291, 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 ]
pragma solidity 0.4.19; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { 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; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title 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]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken, Ownable { 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 onlyOwner { require(_value > 0); require(_value <= balances[msg.sender]); // 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 address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract WePoolToken is BurnableToken { string public constant name = "WePool"; string public constant symbol = "WPL"; uint32 public constant decimals = 18; function WePoolToken() public { totalSupply = 200000000 * 1E18; // 200 million tokens balances[owner] = totalSupply; // owner is crowdsale } } contract WePoolCrowdsale is Ownable { using SafeMath for uint256; uint256 public hardCap; uint256 public reserved; uint256 public tokensSold; // amount of bought tokens uint256 public weiRaised; // total investments uint256 public minPurchase; uint256 public preIcoRate; // how many token units a buyer gets per wei uint256 public icoRate; address public wallet; // for withdrawal address public tokenWallet; // for reserving tokens uint256 public icoStartTime; uint256 public preIcoStartTime; address[] public investorsArray; mapping (address => uint256) public investors; //address -> amount WePoolToken public token; modifier icoEnded() { require(now > (icoStartTime + 30 days)); _; } /** * @dev Constructor to WePoolCrowdsale contract */ function WePoolCrowdsale(uint256 _preIcoStartTime, uint256 _icoStartTime) public { require(_preIcoStartTime > now); require(_icoStartTime > _preIcoStartTime + 7 days); preIcoStartTime = _preIcoStartTime; icoStartTime = _icoStartTime; minPurchase = 0.1 ether; preIcoRate = 0.00008 ether; icoRate = 0.0001 ether; hardCap = 200000000 * 1E18; // 200 million tokens * decimals token = new WePoolToken(); reserved = hardCap.mul(35).div(100); hardCap = hardCap.sub(reserved); // tokens left for sale (200m - 70 = 130) wallet = owner; tokenWallet = owner; } /** * @dev Function set new wallet address. Wallet is used for withdrawal * @param newWallet Address of new wallet. */ function changeWallet(address newWallet) public onlyOwner { require(newWallet != address(0)); wallet = newWallet; } /** * @dev Function set new token wallet address * @dev Token wallet is used for reserving tokens for founders * @param newAddress Address of new Token Wallet */ function changeTokenWallet(address newAddress) public onlyOwner { require(newAddress != address(0)); tokenWallet = newAddress; } /** @dev Function set new preIco token price @param newRate New preIco price per token */ function changePreIcoRate(uint256 newRate) public onlyOwner { require(newRate > 0); preIcoRate = newRate; } /** @dev Function set new Ico token price @param newRate New Ico price per token */ function changeIcoRate(uint256 newRate) public onlyOwner { require(newRate > 0); icoRate = newRate; } /** * @dev Function set new preIco start time * @param newTime New preIco start time */ function changePreIcoStartTime(uint256 newTime) public onlyOwner { require(now < preIcoStartTime); require(newTime > now); require(icoStartTime > newTime + 7 days); preIcoStartTime = newTime; } /** * @dev Function set new Ico start time * @param newTime New Ico start time */ function changeIcoStartTime(uint256 newTime) public onlyOwner { require(now < icoStartTime); require(newTime > now); require(newTime > preIcoStartTime + 7 days); icoStartTime = newTime; } /** * @dev Function burn all unsold Tokens (balance of crowdsale) * @dev Ico should be ended */ function burnUnsoldTokens() public onlyOwner icoEnded { token.burn(token.balanceOf(this)); } /** * @dev Function transfer all raised money to the founders wallet * @dev Ico should be ended */ function withdrawal() public onlyOwner icoEnded { wallet.transfer(this.balance); } /** * @dev Function reserve tokens for founders and bounty program * @dev Ico should be ended */ function getReservedTokens() public onlyOwner icoEnded { require(reserved > 0); uint256 amount = reserved; reserved = 0; token.transfer(tokenWallet, amount); } /** * @dev Fallback function */ function() public payable { buyTokens(); } /** * @dev Function for investments. */ function buyTokens() public payable { address inv = msg.sender; uint256 weiAmount = msg.value; require(weiAmount >= minPurchase); uint256 rate; uint256 tokens; uint256 cleanWei; // amount of wei to use for purchase excluding change and hardcap overflows uint256 change; if (now > preIcoStartTime && now < (preIcoStartTime + 7 days)) { rate = preIcoRate; } else if (now > icoStartTime && now < (icoStartTime + 30 days)) { rate = icoRate; } require(rate > 0); tokens = (weiAmount.mul(1E18)).div(rate); // check hardCap if (tokensSold.add(tokens) > hardCap) { tokens = hardCap.sub(tokensSold); cleanWei = tokens.mul(rate).div(1E18); change = weiAmount.sub(cleanWei); } else { cleanWei = weiAmount; } // check, if this investor already included if (investors[inv] == 0) { investorsArray.push(inv); investors[inv] = tokens; } else { investors[inv] = investors[inv].add(tokens); } tokensSold = tokensSold.add(tokens); weiRaised = weiRaised.add(cleanWei); token.transfer(inv, tokens); // send back change if (change > 0) { inv.transfer(change); } } /** * @dev Function returns the number of investors. * @return uint256 Number of investors. */ function getInvestorsLength() public view returns(uint256) { return investorsArray.length; } }
* @dev Function set new preIco start time @param newTime New preIco start time/
function changePreIcoStartTime(uint256 newTime) public onlyOwner { require(now < preIcoStartTime); require(newTime > now); require(icoStartTime > newTime + 7 days); preIcoStartTime = newTime; }
15,845,008
[ 1, 2083, 444, 394, 675, 45, 2894, 787, 813, 225, 394, 950, 1166, 675, 45, 2894, 787, 813, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 1386, 45, 2894, 13649, 12, 11890, 5034, 394, 950, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 3338, 411, 675, 45, 2894, 13649, 1769, 203, 3639, 2583, 12, 2704, 950, 405, 2037, 1769, 203, 3639, 2583, 12, 10764, 13649, 405, 394, 950, 397, 2371, 4681, 1769, 203, 3639, 675, 45, 2894, 13649, 273, 394, 950, 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 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Airlines struct Airline { string name; bool exists; bool registered; uint256 invested; uint256 voteCount; } address private contractOwner; // Account used to deploy contract address private appContractOwner; // Address of application contract owner bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => Airline) private airlines; // Airline companies participating in contract uint256 private airlineCount = 0; // Number of airline companies participating in contract mapping(bytes32 => address[]) private flights; // Map of flight of insurees mapping(address => uint256) private insureesBalance; // Map of insurees balance /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(address firstAirline, string firstAirlineName) public { contractOwner = msg.sender; _addAirline(firstAirline, firstAirlineName); _registerAirline(firstAirline); } /********************************************************************************************/ /* 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"); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the Application "ContractOwner" account to be the function caller */ modifier requireAppContractOwner() { require(msg.sender == appContractOwner, "Caller is not App contract owner"); _; } /** * @dev Modifier that requires the Airline be registered */ modifier requireRegistredAirline(address applicantAirline) { require(airlines[applicantAirline].registered == true, "Applicant air line is not a registered Airline"); _; } /** * @dev Modifier that requires the Airline has funds */ modifier requireFundedAirline(address applicantAirline) { require(airlines[applicantAirline].invested >= (10 ether), "Applicant air line has not enough fund"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public 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 */ /********************************************************************************************/ /** * Authorize application contract owner calls this contract. Only this address can call * data contract business methods. */ function authorizeCaller(address _appContractOwner) external requireIsOperational requireContractOwner { appContractOwner = _appContractOwner; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function addAirline (address airline, address newAirline, string name) external payable requireIsOperational requireAppContractOwner requireRegistredAirline(airline) requireFundedAirline(airline) { _addAirline(newAirline, name); } /** * @dev Add an airline to the registration queue * */ function _addAirline (address newCompany, string name) private { Airline memory airline = Airline(name, true, false, 0, 0); airlines[newCompany] = airline; airlineCount++; } /** * @dev Aprove an Airline to participate to insurance * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airline, address applicantAirline) external requireIsOperational requireAppContractOwner requireRegistredAirline(airline) requireFundedAirline(airline) { _registerAirline(applicantAirline); } /** * @dev Aprove an Airline to participate to insurance * Can only be called from FlightSuretyApp contract * */ function _registerAirline(address applicantAirline) private { airlines[applicantAirline].registered = true; } /** * @dev Allowed airline votes to new one airline */ function vote(address airline, address applicantAirline) external requireIsOperational requireAppContractOwner requireRegistredAirline(airline) requireFundedAirline(airline) { airlines[applicantAirline].voteCount++; } /** * @dev Add funds to airline address */ function addFundsToAirline(address airline, uint256 value) external requireIsOperational requireAppContractOwner { airlines[airline].invested += value; } /** * @dev Buy insurance for a flight * */ function buy(address airline, string flight, uint256 timestamp, address insuree) external payable requireIsOperational requireAppContractOwner { address(this).transfer(msg.value); bytes32 flightKey = getFlightKey(airline, flight, timestamp); flights[flightKey].push(insuree); } /** * @dev Credits payouts to insurees */ function creditInsurees(address airline, string flight, uint256 timestamp, uint256 value) external requireIsOperational requireAppContractOwner { bytes32 flightKey = getFlightKey(airline, flight, timestamp); for (uint256 i = 0; i < flights[flightKey].length; i++) { uint256 currentBalance = insureesBalance[flights[flightKey][i]]; uint256 newBalance = currentBalance + (value); insureesBalance[flights[flightKey][i]] = newBalance; } delete flights[flightKey]; } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address insuree) external payable requireIsOperational requireAppContractOwner { require(insureesBalance[insuree] > 0, "This insuree has no balance."); uint256 value = insureesBalance[insuree]; insureesBalance[insuree] = 0; insuree.transfer(value); } /** * Returns a key to access flights map */ function getFlightKey (address airline, string memory flight, uint256 timestamp) private pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Returns information about Airline. */ function getAirline(address airlineAddress) external view requireIsOperational requireAppContractOwner returns(string name, bool registered, uint invested, uint voteCount) { Airline memory airline = airlines[airlineAddress]; return(airline.name, airline.registered, airline.invested, airline.voteCount); } /** * @dev Check Airline existance */ function airlineExists(address airline) external view requireIsOperational requireAppContractOwner returns (bool) { return airlines[airline].exists; } /** * @dev Returns the number of Airline votes. */ function getAirlineVoteCount(address airlineAddress) external view requireIsOperational requireAppContractOwner returns(uint256) { Airline memory airline = airlines[airlineAddress]; return(airline.voteCount); } /** * @dev Returns the number of Airlines. */ function getAirlineCount() external view requireIsOperational requireAppContractOwner returns(uint256) { return airlineCount; } /** * @dev Get insurees credit balance. */ function getInsureeBalance(address insuree) external view requireIsOperational returns(uint256) { return insureesBalance[insuree]; } /** * @dev Fallback function for funding smart contract. * */ function() external payable { } }
Number of airline companies participating in contract
uint256 private airlineCount = 0;
887,607
[ 1, 1854, 434, 23350, 1369, 1161, 27891, 30891, 1776, 316, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3238, 23350, 1369, 1380, 273, 374, 31, 4766, 565, 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 ]
./partial_match/1/0x42dC3fa98F35d21B13Ec4c2923D147d70BCCb92B/sources/Mint.sol
check if user is on whitelist
function testOnWl(bytes calldata signature) external view returns(bool) { require(_signerAddress == keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", bytes32(uint256(uint160(msg.sender))) ) ).recover(signature), "Signer address mismatch."); return true; }
9,259,630
[ 1, 1893, 309, 729, 353, 603, 10734, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1842, 1398, 59, 80, 12, 3890, 745, 892, 3372, 13, 3903, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 2583, 24899, 2977, 264, 1887, 422, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 1548, 92, 3657, 41, 18664, 379, 16724, 2350, 5581, 82, 1578, 3113, 203, 7734, 1731, 1578, 12, 11890, 5034, 12, 11890, 16874, 12, 3576, 18, 15330, 20349, 203, 5411, 262, 203, 3639, 262, 18, 266, 3165, 12, 8195, 3631, 315, 15647, 1758, 13484, 1199, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; // Slight modifiations from base Open Zeppelin Contracts // Consult /oz/README.md for more information import "./oz/ERC20Upgradeable.sol"; import "./oz/ERC20SnapshotUpgradeable.sol"; import "./oz/ERC20PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract ZeroToken is OwnableUpgradeable, ERC20Upgradeable, ERC20PausableUpgradeable, ERC20SnapshotUpgradeable { event AuthorizedSnapshotter(address account); event DeauthorizedSnapshotter(address account); // Mapping which stores all addresses allowed to snapshot mapping(address => bool) authorizedToSnapshot; function initialize(string memory name, string memory symbol) public initializer { __Ownable_init(); __ERC20_init(name, symbol); __ERC20Snapshot_init(); __ERC20Pausable_init(); } // Call this on the implementation contract (not the proxy) function initializeImplementation() public initializer { __Ownable_init(); _pause(); } /** * Mints new tokens. * @param account the account to mint the tokens for * @param amount the amount of tokens to mint. */ function mint(address account, uint256 amount) external onlyOwner { _mint(account, amount); } /** * Burns tokens from an address. * @param account the account to mint the tokens for * @param amount the amount of tokens to mint. */ function burn(address account, uint256 amount) external onlyOwner { _burn(account, amount); } /** * Pauses the token contract preventing any token mint/transfer/burn operations. * Can only be called if the contract is unpaused. */ function pause() external onlyOwner { _pause(); } /** * Unpauses the token contract preventing any token mint/transfer/burn operations * Can only be called if the contract is paused. */ function unpause() external onlyOwner { _unpause(); } /** * Creates a token balance snapshot. Ideally this would be called by the * controlling DAO whenever a proposal is made. */ function snapshot() external returns (uint256) { require( authorizedToSnapshot[_msgSender()] || _msgSender() == owner(), "zDAOToken: Not authorized to snapshot" ); return _snapshot(); } /** * Authorizes an account to take snapshots * @param account The account to authorize */ function authorizeSnapshotter(address account) external onlyOwner { require( !authorizedToSnapshot[account], "zDAOToken: Account already authorized" ); authorizedToSnapshot[account] = true; emit AuthorizedSnapshotter(account); } /** * Deauthorizes an account to take snapshots * @param account The account to de-authorize */ function deauthorizeSnapshotter(address account) external onlyOwner { require(authorizedToSnapshot[account], "zDAOToken: Account not authorized"); authorizedToSnapshot[account] = false; emit DeauthorizedSnapshotter(account); } /** * Utility function to transfer tokens to many addresses at once. * @param recipients The addresses to send tokens to * @param amount The amount of tokens to send * @return Boolean if the transfer was a success */ function transferBulk(address[] calldata recipients, uint256 amount) external returns (bool) { address sender = _msgSender(); uint256 total = amount * recipients.length; require( _balances[sender] >= total, "ERC20: transfer amount exceeds balance" ); require(!paused(), "ERC20Pausable: token transfer while paused"); _balances[sender] -= total; _updateAccountSnapshot(sender); for (uint256 i = 0; i < recipients.length; ++i) { address recipient = recipients[i]; require(recipient != address(0), "ERC20: transfer to the zero address"); // Note: _beforeTokenTransfer isn't called here // This function emulates what it would do (paused and snapshot) _balances[recipient] += amount; _updateAccountSnapshot(recipient); emit Transfer(sender, recipient, amount); } return true; } /** * Utility function to transfer tokens to many addresses at once. * @param sender The address to send the tokens from * @param recipients The addresses to send tokens to * @param amount The amount of tokens to send * @return Boolean if the transfer was a success */ function transferFromBulk( address sender, address[] calldata recipients, uint256 amount ) external returns (bool) { require(!paused(), "ERC20Pausable: token transfer while paused"); uint256 total = amount * recipients.length; require( _balances[sender] >= total, "ERC20: transfer amount exceeds balance" ); // Ensure enough allowance uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= total, "ERC20: transfer total exceeds allowance" ); _approve(sender, _msgSender(), currentAllowance - total); _balances[sender] -= total; _updateAccountSnapshot(sender); for (uint256 i = 0; i < recipients.length; ++i) { address recipient = recipients[i]; require(recipient != address(0), "ERC20: transfer to the zero address"); // Note: _beforeTokenTransfer isn't called here // This function emulates what it would do (paused and snapshot) _balances[recipient] += amount; _updateAccountSnapshot(recipient); emit Transfer(sender, recipient, amount); } return true; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override( ERC20PausableUpgradeable, ERC20SnapshotUpgradeable, ERC20Upgradeable ) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { // Diff from Open Zeppelin Standard mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ArraysUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable { function __ERC20Snapshot_init() internal initializer { __Context_init_unchained(); __ERC20Snapshot_init_unchained(); } function __ERC20Snapshot_init_unchained() internal initializer {} // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using ArraysUpgradeable for uint256[]; using CountersUpgradeable for CountersUpgradeable.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. CountersUpgradeable.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 virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // 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) internal { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() internal { _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]; } } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer {} /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_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 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.8.0; import "./math/MathUpgradeable.sol"; /** * @dev Collection of functions related to array types. */ library ArraysUpgradeable { /** * @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 = MathUpgradeable.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @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); } } // 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; }
solhint-disable-next-line max-line-length 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.
function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); require( snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id" ); uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); return (true, snapshots.values[index]); } }
6,979,442
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 943, 17, 1369, 17, 2469, 5203, 279, 923, 4439, 353, 23264, 16, 1915, 854, 8925, 28550, 30, 225, 279, 13, 1021, 23264, 460, 1703, 486, 4358, 1839, 326, 4439, 1703, 9830, 18, 17189, 16, 279, 4439, 1241, 1703, 5903, 225, 2522, 364, 333, 612, 16, 471, 777, 4041, 4439, 3258, 854, 10648, 2353, 326, 3764, 1245, 18, 1021, 460, 716, 13955, 225, 358, 333, 612, 353, 326, 783, 1245, 18, 225, 324, 13, 1021, 23264, 460, 1703, 4358, 1839, 326, 4439, 1703, 9830, 18, 17189, 16, 1915, 903, 506, 392, 1241, 598, 326, 225, 3764, 612, 16, 471, 2097, 460, 353, 326, 1245, 358, 327, 18, 225, 276, 13, 16053, 12808, 4591, 2522, 1839, 326, 3764, 1245, 16, 471, 326, 23264, 460, 1703, 5137, 4358, 18, 6149, 903, 506, 225, 1158, 1241, 364, 326, 3764, 612, 30, 326, 460, 716, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 389, 1132, 861, 12, 11890, 5034, 4439, 548, 16, 10030, 87, 2502, 12808, 13, 203, 565, 3238, 203, 565, 1476, 203, 565, 1135, 261, 6430, 16, 2254, 5034, 13, 203, 225, 288, 203, 565, 2583, 12, 11171, 548, 405, 374, 16, 315, 654, 39, 3462, 4568, 30, 612, 353, 374, 8863, 203, 565, 2583, 12, 203, 1377, 4439, 548, 1648, 389, 2972, 4568, 548, 18, 2972, 9334, 203, 1377, 315, 654, 39, 3462, 4568, 30, 1661, 19041, 612, 6, 203, 565, 11272, 203, 203, 203, 565, 2254, 5034, 770, 273, 12808, 18, 2232, 18, 4720, 21328, 12, 11171, 548, 1769, 203, 203, 565, 309, 261, 1615, 422, 12808, 18, 2232, 18, 2469, 13, 288, 203, 1377, 327, 261, 5743, 16, 374, 1769, 203, 1377, 327, 261, 3767, 16, 12808, 18, 2372, 63, 1615, 19226, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x880d6adb5bb4c8a7f578d31a4ddb0c48bc590fa3 //Contract name: Steak //Balance: 0 Ether //Verification Date: 8/25/2017 //Transacion Count: 13 // CODE STARTS HERE pragma solidity ^0.4.15; /** * * STEAK TOKEN (BOV) * * Make bank by eating flank. See https://steaktoken.com. * */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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; modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract SteakToken is Ownable { using SafeMath for uint256; string public name = "Steak Token"; string public symbol = "BOV"; uint public decimals = 18; uint public totalSupply; // Total BOV in circulation. mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed ownerAddress, address indexed spenderAddress, uint256 value); event Mint(address indexed to, uint256 amount); event MineFinished(); function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool) { if(msg.data.length < (2 * 32) + 4) { revert(); } // protect against short address attack balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @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 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Function to mint tokens * @param _to The address that will recieve 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) internal returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } } /** * @title AuctionCrowdsale * @dev The owner starts and ends the crowdsale manually. * Players can make token purchases during the crowdsale * and their tokens can be claimed after the sale ends. * Players receive an amount proportional to their investment. */ contract AuctionCrowdsale is SteakToken { using SafeMath for uint; uint public initialSale; // Amount of BOV tokens being sold during crowdsale. bool public saleStarted; bool public saleEnded; uint public absoluteEndBlock; // Anybody can end the crowdsale and trigger token distribution if beyond this block number. uint256 public weiRaised; // Total amount raised in crowdsale. address[] public investors; // Investor addresses uint public numberOfInvestors; mapping(address => uint256) public investments; // How much each address has invested. mapping(address => bool) public claimed; // Keep track of whether each investor has been awarded their BOV tokens. bool public bovBatchDistributed; // TODO: this can be removed with manual crowdsale end-time uint public initialPrizeWeiValue; // The first steaks mined will be awarded BOV equivalent to this ETH value. Set in Steak() initializer. uint public initialPrizeBov; // Initial mining prize in BOV units. Set in endCrowdsale() or endCrowdsalePublic(). uint public dailyHashExpires; // When the dailyHash expires. Will be roughly around 3am EST. /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event TokenInvestment(address indexed purchaser, address indexed beneficiary, uint256 value); // Sending ETH to this contract's address registers the investment. function () payable { invest(msg.sender); } // Participate in the crowdsale. // Records how much each address has invested. function invest(address beneficiary) payable { require(beneficiary != 0x0); require(validInvestment()); uint256 weiAmount = msg.value; uint investedAmount = investments[beneficiary]; forwardFunds(); if (investedAmount > 0) { // If they've already invested, increase their balance. investments[beneficiary] = investedAmount + weiAmount; // investedAmount.add(weiAmount); } else { // If new investor investors.push(beneficiary); numberOfInvestors += 1; investments[beneficiary] = weiAmount; } weiRaised = weiRaised.add(weiAmount); TokenInvestment(msg.sender, beneficiary, weiAmount); } // @return true if the transaction can invest function validInvestment() internal constant returns (bool) { bool withinPeriod = saleStarted && !saleEnded; bool nonZeroPurchase = (msg.value > 0); return withinPeriod && nonZeroPurchase; } // Distribute 10M tokens proportionally amongst all investors. Can be called by anyone after the crowdsale ends. // ClaimTokens() can be run by individuals to claim their tokens. function distributeAllTokens() public { require(!bovBatchDistributed); require(crowdsaleHasEnded()); // Allocate BOV proportionally to each investor. for (uint i=0; i < numberOfInvestors; i++) { address investorAddr = investors[i]; if (!claimed[investorAddr]) { // If the investor hasn't already claimed their BOV. claimed[investorAddr] = true; uint amountInvested = investments[investorAddr]; uint bovEarned = amountInvested.mul(initialSale).div(weiRaised); mint(investorAddr, bovEarned); } } bovBatchDistributed = true; } // Claim your BOV; allocates BOV proportionally to this investor. // Can be called by investors to claim their BOV after the crowdsale ends. // distributeAllTokens() is a batch alternative to this. function claimTokens(address origAddress) public { require(crowdsaleHasEnded()); require(claimed[origAddress] == false); uint amountInvested = investments[origAddress]; uint bovEarned = amountInvested.mul(initialSale).div(weiRaised); claimed[origAddress] = true; mint(origAddress, bovEarned); } // Investors: see how many BOV you are currently entitled to (before the end of the crowdsale and distribution of tokens). function getCurrentShare(address addr) public constant returns (uint) { require(!bovBatchDistributed && !claimed[addr]); // Tokens cannot have already been distributed. uint amountInvested = investments[addr]; uint currentBovShare = amountInvested.mul(initialSale).div(weiRaised); return currentBovShare; } // send ether to the fund collection wallet function forwardFunds() internal { owner.transfer(msg.value); } // The owner manually starts the crowdsale at a pre-determined time. function startCrowdsale() onlyOwner { require(!saleStarted && !saleEnded); saleStarted = true; } // endCrowdsale() and endCrowdsalePublic() moved to Steak contract // Normally, the owner will end the crowdsale at the pre-determined time. function endCrowdsale() onlyOwner { require(saleStarted && !saleEnded); dailyHashExpires = now; // Will end crowdsale at 3am EST, so expiration time will roughly be around 3am. saleEnded = true; setInitialPrize(); } // Normally, Madame BOV ends the crowdsale at the pre-determined time, but if Madame BOV fails to do so, anybody can trigger endCrowdsalePublic() after absoluteEndBlock. function endCrowdsalePublic() public { require(block.number > absoluteEndBlock); require(saleStarted && !saleEnded); dailyHashExpires = now; saleEnded = true; setInitialPrize(); } // Calculate initial mining prize (0.0357 ether's worth of BOV). This is called in endCrowdsale(). function setInitialPrize() internal returns (uint) { require(crowdsaleHasEnded()); require(initialPrizeBov == 0); // Can only be set once uint tokenUnitsPerWei = initialSale.div(weiRaised); initialPrizeBov = tokenUnitsPerWei.mul(initialPrizeWeiValue); return initialPrizeBov; } // @return true if crowdsale event has ended function crowdsaleHasEnded() public constant returns (bool) { return saleStarted && saleEnded; } function getInvestors() public returns (address[]) { return investors; } } contract Steak is AuctionCrowdsale { // using SafeMath for uint; bytes32 public dailyHash; // The last five digits of the dailyHash must be included in steak pictures. Submission[] public submissions; // All steak pics uint public numSubmissions; Submission[] public approvedSubmissions; mapping (address => uint) public memberId; // Get member ID from address. Member[] public members; // Index is memberId uint public halvingInterval; // BOV award is halved every x steaks uint public numberOfHalvings; // How many times the BOV reward per steak is halved before it returns 0. uint public lastMiningBlock; // No mining after this block. Set in initializer. bool public ownerCredited; // Has the owner been credited BOV yet? event PicAdded(address msgSender, uint submissionID, address recipient, bytes32 propUrl); // Need msgSender so we can watch for this event. event Judged(uint submissionID, bool position, address voter, bytes32 justification); event MembershipChanged(address member, bool isMember); struct Submission { address recipient; // Would-be BOV recipient bytes32 url; // IMGUR url; 32-char max bool judged; // Has an admin voted? bool submissionApproved;// Has it been approved? address judgedBy; // Admin who judged this steak bytes32 adminComments; // Admin should leave feedback on non-approved steaks. 32-char max. bytes32 todaysHash; // The hash in the image should match this hash. uint awarded; // Amount awarded } // Members can vote on steak struct Member { address member; bytes32 name; uint memberSince; } modifier onlyMembers { require(memberId[msg.sender] != 0); // member id must be in the mapping _; } function Steak() { owner = msg.sender; initialSale = 10000000 * 1000000000000000000; // 10M BOV units are awarded in the crowdsale. // Normally, the owner both starts and ends the crowdsale. // To guarantee that the crowdsale ends at some maximum point (at that tokens are distributed), // we calculate the absoluteEndBlock, the block beyond which anybody can end the crowdsale and distribute tokens. uint blocksPerHour = 212; uint maxCrowdsaleLifeFromLaunchDays = 40; // After about this many days from launch, anybody can end the crowdsale and distribute / claim their tokens. absoluteEndBlock = block.number + (blocksPerHour * 24 * maxCrowdsaleLifeFromLaunchDays); uint miningDays = 365; // Approximately how many days BOV can be mined from the launch of the contract. lastMiningBlock = block.number + (blocksPerHour * 24 * miningDays); dailyHashExpires = now; halvingInterval = 500; // How many steaks get awarded the given getSteakPrize() amount before the reward is halved. numberOfHalvings = 8; // How many times the steak prize gets halved before no more prize is awarded. // initialPrizeWeiValue = 50 finney; // 0.05 ether == 50 finney == 2.80 USD * 5 == 14 USD initialPrizeWeiValue = (357 finney / 10); // 0.0357 ether == 35.7 finney == 2.80 USD * 3.57 == 9.996 USD // To finish initializing, owner calls initMembers() and creditOwner() after launch. } // Add Madame BOV as a beef judge. function initMembers() onlyOwner { addMember(0, ''); // Must add an empty first member addMember(msg.sender, 'Madame BOV'); } // Send 1M BOV to Madame BOV. function creditOwner() onlyOwner { require(!ownerCredited); uint ownerAward = initialSale / 10; // 10% of the crowdsale amount. ownerCredited = true; // Can only be run once. mint(owner, ownerAward); } /* Add beef judge */ function addMember(address targetMember, bytes32 memberName) onlyOwner { uint id; if (memberId[targetMember] == 0) { memberId[targetMember] = members.length; id = members.length++; members[id] = Member({member: targetMember, memberSince: now, name: memberName}); } else { id = memberId[targetMember]; // Member m = members[id]; } MembershipChanged(targetMember, true); } function removeMember(address targetMember) onlyOwner { if (memberId[targetMember] == 0) revert(); memberId[targetMember] = 0; for (uint i = memberId[targetMember]; i<members.length-1; i++){ members[i] = members[i+1]; } delete members[members.length-1]; members.length--; } /* Submit a steak picture. (After crowdsale has ended.) * WARNING: Before taking the picture, call getDailyHash() and minutesToPost() * so you can be sure that you have the correct dailyHash and that it won't expire before you post it. */ function submitSteak(address addressToAward, bytes32 steakPicUrl) returns (uint submissionID) { require(crowdsaleHasEnded()); require(block.number <= lastMiningBlock); // Cannot submit beyond this block. submissionID = submissions.length++; // Increase length of array Submission storage s = submissions[submissionID]; s.recipient = addressToAward; s.url = steakPicUrl; s.judged = false; s.submissionApproved = false; s.todaysHash = getDailyHash(); // Each submission saves the hash code the user should take picture of in steak picture. PicAdded(msg.sender, submissionID, addressToAward, steakPicUrl); numSubmissions = submissionID+1; return submissionID; } // Retrieving any Submission must be done via this function, not `submissions()` function getSubmission(uint submissionID) public constant returns (address recipient, bytes32 url, bool judged, bool submissionApproved, address judgedBy, bytes32 adminComments, bytes32 todaysHash, uint awarded) { Submission storage s = submissions[submissionID]; recipient = s.recipient; url = s.url; // IMGUR url judged = s.judged; // Has an admin voted? submissionApproved = s.submissionApproved; // Has it been approved? judgedBy = s.judgedBy; // Admin who judged this steak adminComments = s.adminComments; // Admin should leave feedback on non-approved steaks todaysHash = s.todaysHash; // The hash in the image should match this hash. awarded = s.awarded; // Amount awarded // return (users[index].salaryId, users[index].name, users[index].userAddress, users[index].salary); // return (recipient, url, judged, submissionApproved, judgedBy, adminComments, todaysHash, awarded); } // Members judge steak pics, providing justification if necessary. function judge(uint submissionNumber, bool supportsSubmission, bytes32 justificationText) onlyMembers { Submission storage s = submissions[submissionNumber]; // Get the submission. require(!s.judged); // Musn't be judged. s.judged = true; s.judgedBy = msg.sender; s.submissionApproved = supportsSubmission; s.adminComments = justificationText; // Admin can add comments whether approved or not if (supportsSubmission) { // If it passed muster, credit the user and admin. uint prizeAmount = getSteakPrize(); // Calculate BOV prize s.awarded = prizeAmount; // Record amount in the Submission mint(s.recipient, prizeAmount); // Credit the user's account // Credit the member one-third of the prize amount. uint adminAward = prizeAmount.div(3); mint(msg.sender, adminAward); approvedSubmissions.push(s); } Judged(submissionNumber, supportsSubmission, msg.sender, justificationText); } // Calculate how many BOV are rewarded per approved steak pic. function getSteakPrize() public constant returns (uint) { require(initialPrizeBov > 0); // crowdsale must be over (endCrowdsale() calls setInitialPrize()) uint halvings = numberOfApprovedSteaks().div(halvingInterval); if (halvings > numberOfHalvings) { // After 8 halvings, no more BOV is awarded. return 0; } uint prize = initialPrizeBov; prize = prize >> halvings; // Halve the initial prize "halvings"-number of times. return prize; } function numberOfApprovedSteaks() public constant returns (uint) { return approvedSubmissions.length; } // Always call this before calling dailyHash and submitting a steak. // If expired, the new hash is set to the last block's hash. function getDailyHash() public returns (bytes32) { if (dailyHashExpires > now) { // If the hash hasn't expired yet, return it. return dailyHash; } else { // Udderwise, set the new dailyHash and dailyHashExpiration. // Get hash from the last block. bytes32 newHash = block.blockhash(block.number-1); dailyHash = newHash; // Set the new expiration, jumping ahead in 24-hour increments so the expiration time remains roughly constant from day to day (e.g. 3am). uint nextExpiration = dailyHashExpires + 24 hours; // It will already be expired, so set it to next possible date. while (nextExpiration < now) { // if it's still in the past, advance by 24 hours. nextExpiration += 24 hours; } dailyHashExpires = nextExpiration; return newHash; } } // Returns the amount of minutes to post with the current dailyHash function minutesToPost() public constant returns (uint) { if (dailyHashExpires > now) { return (dailyHashExpires - now) / 60; // returns minutes } else { return 0; } } function currentBlock() public constant returns (uint) { return block.number; } }
No mining after this block. Set in initializer.
uint public lastMiningBlock;
14,056,279
[ 1, 2279, 1131, 310, 1839, 333, 1203, 18, 1000, 316, 12562, 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, 225, 2254, 1071, 1142, 2930, 310, 1768, 31, 10402, 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 ]
./full_match/3/0xc8E379B98F7BBb6BF3e65d9369803Ee248BeaDe0/sources/arbitrage/EtherSnipper.sol
swap tokens UNI-V2if reversePath provided, detect risk
function swapTokensV2(address routerAddress, address[] calldata path, address[] calldata reversePath, uint amountIn, uint amountOutMin, uint tipAmount) public mustAllowed payable { bool fromETH = msg.value - tipAmount > 0; _swapTokensInternalV2(routerAddress, path, amountIn, amountOutMin, fromETH); if (reversePath.length > 0) { require(_stringCompare(reason, "T"), reason); } }
8,185,366
[ 1, 22270, 2430, 19462, 17, 58, 22, 430, 4219, 743, 2112, 16, 5966, 18404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7720, 5157, 58, 22, 12, 2867, 4633, 1887, 16, 1758, 8526, 745, 892, 589, 16, 1758, 8526, 745, 892, 4219, 743, 16, 2254, 3844, 382, 16, 2254, 3844, 1182, 2930, 16, 2254, 9529, 6275, 13, 203, 565, 1071, 1297, 5042, 8843, 429, 288, 203, 3639, 1426, 628, 1584, 44, 273, 1234, 18, 1132, 300, 9529, 6275, 405, 374, 31, 203, 3639, 389, 22270, 5157, 3061, 58, 22, 12, 10717, 1887, 16, 589, 16, 3844, 382, 16, 3844, 1182, 2930, 16, 628, 1584, 44, 1769, 203, 203, 3639, 309, 261, 9845, 743, 18, 2469, 405, 374, 13, 288, 203, 7734, 2583, 24899, 1080, 8583, 12, 10579, 16, 315, 56, 6, 3631, 3971, 1769, 203, 5411, 289, 203, 3639, 289, 203, 540, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xD08eA81B20252228329D5EC8Ca1393c86894442c/sources/EsusuStorage.sol
Total yDai Shares
uint256 TotalShares;
4,902,911
[ 1, 5269, 677, 40, 10658, 2638, 4807, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 10710, 24051, 31, 7734, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./MemberManager.sol"; enum ProposalKind { AddAMember, DeleteAMember, UseOfFunds, CommunityManagement, Activities, ElectionComissionPropsal, DaoReward } enum ProposalStatus { UnderDiscussionOnGithub, Voting, Pending, Running, Rejected, FinishedVoting, Finished } struct ProposalInfo { ProposalKind proposalKind; string title; string outline; string details; string githubURL; uint256 proposalId; uint256 relatedId; address relatedAddress; ProposalStatus proposalStatus; } struct VotingInfo { uint256 votingCount; uint256 yesCount; uint256 noCount; } interface ProposalManagerInterface { function getPropsalInfo(address _targetDaoAddress, uint256 _proposalId) external view returns (ProposalInfo memory); function updateProposalStatus( address _targetDaoAddress, uint256 _proposalId, uint256 _poposalStatus ) external; } /** * ProposalManager */ contract ProposalManager { using Counters for Counters.Counter; MemberManagerInterface private memberManagerContract; address private memberManagerAddress; uint256 public PROPOSAL_PASS_LINE = 60; // Dao address => proposal id => ProposalInfo mapping(address => mapping(uint256 => ProposalInfo)) private proposalInfoes; // Dao address => proposal id => Voting Info mapping(address => mapping(uint256 => VotingInfo)) private votingInfoes; // Dao address => proposal id => ( eoa => Already Voted) mapping(address => mapping(uint256 => mapping(address => bool))) private checkVoted; // Dao address => Counter mapping(address => Counters.Counter) private proposalCounters; event SubmitedProposal( address indexed eoa, string title, uint256 proposalId ); event ChangedProposalStatus( address indexed eoa, uint256 proposalId, ProposalStatus _proposalStatus ); event VotedForProposal(address indexed eoa, uint256 _proposalId); constructor() {} function setMemberManager(address _memberManagerAddress) public { memberManagerContract = MemberManagerInterface(_memberManagerAddress); memberManagerAddress = _memberManagerAddress; } modifier onlyMember(address _targetDaoAddress) { require( memberManagerContract.isMember(_targetDaoAddress, msg.sender), "only member does." ); _; } modifier onlyElectionComission(address _targetDaoAddress) { require( memberManagerContract.isElectionComission( _targetDaoAddress, msg.sender ), "only election comission does." ); _; } /** * 提案を提出する */ function submitProposal( address _targetDaoAddress, ProposalKind _proposalKind, string memory _title, string memory _outline, string memory _details, string memory _githubURL, uint256 _relatedId, address _relatedAddress ) public onlyMember(_targetDaoAddress) { //選挙管理委員提案以外の場合は、任期をチェックする if (_proposalKind != ProposalKind.ElectionComissionPropsal) { if ( memberManagerContract.checkWithinElectionCommisionTerm( _targetDaoAddress ) == false ) { revert("need to select election comission."); } } //選挙管理委員提案でも任期内の場合は変更を不可とする。 if (_proposalKind == ProposalKind.ElectionComissionPropsal) { if ( memberManagerContract.checkWithinElectionCommisionTerm( _targetDaoAddress ) == true ) { revert("still within term."); } } // Proposal Idを1から始めるためにカウントアップ if (proposalCounters[_targetDaoAddress].current() == 0) { proposalCounters[_targetDaoAddress].increment(); } uint256 proposalId = proposalCounters[_targetDaoAddress].current(); proposalInfoes[_targetDaoAddress][proposalId] = ProposalInfo( _proposalKind, _title, _outline, _details, _githubURL, proposalCounters[_targetDaoAddress].current(), _relatedId, _relatedAddress, ProposalStatus.UnderDiscussionOnGithub ); emit SubmitedProposal(msg.sender, _title, proposalId); proposalCounters[_targetDaoAddress].increment(); } /** * 提案のステータスを変更する */ function changeProposalStatus( address _targetDaoAddress, uint256 _proposalId, ProposalStatus _proposalStatus ) public onlyElectionComission(_targetDaoAddress) { require( bytes(proposalInfoes[_targetDaoAddress][_proposalId].title) .length != 0, "Invalid proposal." ); if ( proposalInfoes[_targetDaoAddress][_proposalId].proposalStatus == ProposalStatus.UnderDiscussionOnGithub ) { if ( (_proposalStatus != ProposalStatus.Voting) && (_proposalStatus != ProposalStatus.Pending) && (_proposalStatus != ProposalStatus.Rejected) ) { revert("Invalid Status."); } } else if ( proposalInfoes[_targetDaoAddress][_proposalId].proposalStatus == ProposalStatus.Pending ) { if ( (_proposalStatus != ProposalStatus.Voting) && (_proposalStatus != ProposalStatus.Rejected) && (_proposalStatus != ProposalStatus.UnderDiscussionOnGithub) ) { revert("proposalStatuss."); } } else if ( proposalInfoes[_targetDaoAddress][_proposalId].proposalStatus == ProposalStatus.Voting ) { if ((_proposalStatus != ProposalStatus.FinishedVoting)) { revert("Invalid Status."); } } else if ( proposalInfoes[_targetDaoAddress][_proposalId].proposalStatus == ProposalStatus.Running ) { if ((_proposalStatus != ProposalStatus.Finished)) { revert("Invalid Status."); } } else if ( (proposalInfoes[_targetDaoAddress][_proposalId].proposalStatus == ProposalStatus.Finished) || (proposalInfoes[_targetDaoAddress][_proposalId].proposalStatus == ProposalStatus.Rejected) ) { revert("Invalid Status."); } if (_proposalStatus == ProposalStatus.FinishedVoting) { proposalInfoes[_targetDaoAddress][_proposalId] .proposalStatus = _checkVotingResult( _targetDaoAddress, _proposalId ); memberManagerContract.countupTermCounter(_targetDaoAddress); } else if (_proposalStatus == ProposalStatus.Voting) { proposalInfoes[_targetDaoAddress][_proposalId] .proposalStatus = _proposalStatus; _startVoting(_targetDaoAddress, _proposalId); } else if (_proposalStatus == ProposalStatus.Running) { revert("Invalid Status."); } else { proposalInfoes[_targetDaoAddress][_proposalId] .proposalStatus = _proposalStatus; } emit ChangedProposalStatus(msg.sender, _proposalId, _proposalStatus); } /** * 投票する */ function voteForProposal( address _targetDaoAddress, uint256 _proposalId, bool yes ) public onlyMember(_targetDaoAddress) { require( proposalInfoes[_targetDaoAddress][_proposalId].proposalStatus == ProposalStatus.Voting, "Now can not vote." ); require( checkVoted[_targetDaoAddress][_proposalId][msg.sender] == false, "Already voted." ); votingInfoes[_targetDaoAddress][_proposalId].votingCount++; if (yes) { votingInfoes[_targetDaoAddress][_proposalId].yesCount++; } else { votingInfoes[_targetDaoAddress][_proposalId].noCount++; } checkVoted[_targetDaoAddress][_proposalId][msg.sender] = true; emit VotedForProposal(msg.sender, _proposalId); } /** * 提案の一覧を取得する */ function getProposalList(address _targetDaoAddress) public view returns (ProposalInfo[] memory) { uint256 index = 0; if (proposalCounters[_targetDaoAddress].current() != 0) { index = proposalCounters[_targetDaoAddress].current() - 1; } ProposalInfo[] memory proposalList = new ProposalInfo[](index); for ( uint256 i = 1; i < proposalCounters[_targetDaoAddress].current(); i++ ) { if (bytes(proposalInfoes[_targetDaoAddress][i].title).length != 0) { proposalList[i - 1] = proposalInfoes[_targetDaoAddress][i]; } } return proposalList; } /** * 投票結果を取得する */ function getVotingResult(address _targetDaoAddress, uint256 _proposalId) public view returns (VotingInfo memory) { return votingInfoes[_targetDaoAddress][_proposalId]; } /** * 投票を開始する */ function _startVoting(address _targetDaoAddress, uint256 _proposalId) internal { votingInfoes[_targetDaoAddress][_proposalId] = VotingInfo(0, 0, 0); } /** * 投票結果をチェックする。 */ function _checkVotingResult(address _targetDaoAddress, uint256 _proposalId) internal view returns (ProposalStatus) { uint256 memberCount = memberManagerContract.getMemberCount( _targetDaoAddress ); if ( (votingInfoes[_targetDaoAddress][_proposalId].yesCount * 100) / memberCount >= PROPOSAL_PASS_LINE ) { return ProposalStatus.Running; } else { return ProposalStatus.Rejected; } } /** * 該当の提案状態を取得する */ function getPropsalInfo(address _targetDaoAddress, uint256 _proposalId) external view returns (ProposalInfo memory) { return proposalInfoes[_targetDaoAddress][_proposalId]; } /** * 該当する提案のステータスを更新する */ function updateProposalStatus( address _targetDaoAddress, uint256 _proposalId, uint256 _poposalStatus ) external { require(msg.sender != tx.origin, "can not call directly."); require( msg.sender == memberManagerAddress || msg.sender == _targetDaoAddress, "invalid origin." ); // require(memberManagerContract.isMember(_targetDaoAddress, msg.sender),"only member does."); proposalInfoes[_targetDaoAddress][_proposalId] .proposalStatus = ProposalStatus(_poposalStatus); } }
* 提案を提出する/選挙管理委員提案以外の場合は、任期をチェックする選挙管理委員提案でも任期内の場合は変更を不可とする。 Proposal Idを1から始めるためにカウントアップ
function submitProposal( address _targetDaoAddress, ProposalKind _proposalKind, string memory _title, string memory _outline, string memory _details, string memory _githubURL, uint256 _relatedId, address _relatedAddress ) public onlyMember(_targetDaoAddress) { if (_proposalKind != ProposalKind.ElectionComissionPropsal) { if ( memberManagerContract.checkWithinElectionCommisionTerm( _targetDaoAddress ) == false ) { revert("need to select election comission."); } } if (_proposalKind == ProposalKind.ElectionComissionPropsal) { if ( memberManagerContract.checkWithinElectionCommisionTerm( _targetDaoAddress ) == true ) { revert("still within term."); } } if (proposalCounters[_targetDaoAddress].current() == 0) { proposalCounters[_targetDaoAddress].increment(); } uint256 proposalId = proposalCounters[_targetDaoAddress].current(); proposalInfoes[_targetDaoAddress][proposalId] = ProposalInfo( _proposalKind, _title, _outline, _details, _githubURL, proposalCounters[_targetDaoAddress].current(), _relatedId, _relatedAddress, ProposalStatus.UnderDiscussionOnGithub ); emit SubmitedProposal(msg.sender, _title, proposalId); proposalCounters[_targetDaoAddress].increment(); }
1,830,086
[ 1, 167, 242, 243, 167, 99, 235, 164, 229, 245, 167, 242, 243, 166, 234, 123, 164, 228, 252, 164, 229, 238, 19, 170, 228, 121, 167, 239, 252, 168, 111, 99, 168, 243, 233, 166, 105, 247, 166, 246, 99, 167, 242, 243, 167, 99, 235, 165, 124, 103, 166, 102, 249, 164, 228, 111, 166, 259, 117, 166, 243, 235, 164, 228, 112, 164, 227, 228, 165, 124, 124, 167, 255, 258, 164, 229, 245, 164, 230, 228, 164, 229, 105, 164, 230, 230, 164, 229, 112, 164, 228, 252, 164, 229, 238, 170, 228, 121, 167, 239, 252, 168, 111, 99, 168, 243, 233, 166, 105, 247, 166, 246, 99, 167, 242, 243, 167, 99, 235, 164, 228, 105, 164, 229, 229, 165, 124, 124, 167, 255, 258, 166, 233, 232, 164, 228, 111, 166, 259, 117, 166, 243, 235, 164, 228, 112, 166, 102, 236, 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, 4879, 14592, 12, 203, 3639, 1758, 389, 3299, 11412, 1887, 16, 203, 3639, 19945, 5677, 389, 685, 8016, 5677, 16, 203, 3639, 533, 3778, 389, 2649, 16, 203, 3639, 533, 3778, 389, 25134, 16, 203, 3639, 533, 3778, 389, 6395, 16, 203, 3639, 533, 3778, 389, 6662, 1785, 16, 203, 3639, 2254, 5034, 389, 9243, 548, 16, 203, 3639, 1758, 389, 9243, 1887, 203, 565, 262, 1071, 1338, 4419, 24899, 3299, 11412, 1887, 13, 288, 203, 3639, 309, 261, 67, 685, 8016, 5677, 480, 19945, 5677, 18, 29110, 799, 19710, 5047, 287, 13, 288, 203, 5411, 309, 261, 203, 7734, 3140, 1318, 8924, 18, 1893, 18949, 29110, 12136, 1951, 4065, 12, 203, 10792, 389, 3299, 11412, 1887, 203, 7734, 262, 422, 629, 203, 5411, 262, 288, 203, 7734, 15226, 2932, 14891, 358, 2027, 25526, 532, 19710, 1199, 1769, 203, 5411, 289, 203, 3639, 289, 203, 3639, 309, 261, 67, 685, 8016, 5677, 422, 19945, 5677, 18, 29110, 799, 19710, 5047, 287, 13, 288, 203, 5411, 309, 261, 203, 7734, 3140, 1318, 8924, 18, 1893, 18949, 29110, 12136, 1951, 4065, 12, 203, 10792, 389, 3299, 11412, 1887, 203, 7734, 262, 422, 638, 203, 5411, 262, 288, 203, 7734, 15226, 2932, 334, 737, 3470, 2481, 1199, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 685, 8016, 18037, 63, 67, 3299, 11412, 1887, 8009, 2972, 1435, 422, 374, 13, 288, 203, 5411, 14708, 18037, 63, 67, 3299, 11412, 1887, 8009, 15016, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 14708, 548, 2 ]
// 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 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; /** * @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 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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @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; } uint256[50] private __gap; } // 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; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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); } // 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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the 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 "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; import "./interfaces/IUninterestedUnicorns.sol"; import "./interfaces/ICandyToken.sol"; contract UniQuest is AccessControlUpgradeable, ERC721HolderUpgradeable, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; struct Quest { address questOwner; uint256 questLevel; uint256 questStart; uint256 questEnd; uint256 lastClaim; uint256 clanMultiplier; uint256 rareMultiplier; uint256 lengthMultiplier; uint256[] unicornIds; QuestState questState; } struct ClanCounter { uint8 airCount; uint8 earthCount; uint8 fireCount; uint8 waterCount; uint8 darkCount; uint8 pureCount; } // Enums enum Clans { AIR, EARTH, FIRE, WATER, DARK, PURE } enum QuestState { IN_PROGRESS, ENDED } IUninterestedUnicorns public UU; ICandyToken public UCD; uint256 public baseReward; uint256 public baseRoboReward; uint256 public baseGoldenReward; uint256 private timescale; uint256[] public clanMultipliers; uint256[] public rareMultipliers; uint256[] public lengthMultipliers; uint256[] public questLengths; bytes public clans; mapping(uint256 => Quest) public quests; mapping(address => uint256[]) public userQuests; // Maps user address to questIds mapping(uint256 => uint256) public onQuest; // Maps tokenId to QuestId (0 = not questing) mapping(uint256 => uint256) clanCounter; mapping(uint256 => bool) private isRoboUni; mapping(uint256 => bool) private isGoldenUni; mapping(uint256 => uint256) private HODLLastClaim; // Private Variables CountersUpgradeable.Counter private _questId; bool private initialized; // Reserve Storage uint256[50] private ______gap; // Events event QuestStarted( address indexed user, uint256 questId, uint256[] unicornIds, uint256 questLevel, uint256 questStart, uint256 questEnd ); event QuestEnded(address indexed user, uint256 questId, uint256 endDate); event RewardClaimed( address indexed user, uint256 amount, uint256 claimTime ); event QuestUpgraded( address indexed user, uint256 questId, uint256 questLevel ); // Modifiers modifier onlyAdmin() { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "UninterestedUnicorns: OnlyAdmin" ); _; } function __UniQuest_init( address uu, uint256 _baseReward, uint256 _baseRoboReward, uint256 _baseGoldenReward, address deployer, address treasury ) public initializer { require(!initialized, "Contract instance has already been initialized"); __AccessControl_init(); __ReentrancyGuard_init(); __ERC721Holder_init(); // Constructor init _setupRole(DEFAULT_ADMIN_ROLE, deployer); // To revoke access after functions are set grantRole(DEFAULT_ADMIN_ROLE, treasury); baseReward = _baseReward; baseRoboReward = _baseRoboReward; baseGoldenReward = _baseGoldenReward; UU = IUninterestedUnicorns(uu); clanMultipliers = [10000, 10000, 10200, 10400, 10600, 11000]; rareMultipliers = [10000, 10200, 10400, 10600, 10800, 11000]; lengthMultipliers = [10000, 10500, 11000]; questLengths = [30 days, 90 days, 180 days]; timescale = 1 days; initialized = true; } // ------------------------- USER FUNCTION --------------------------- /// @dev Start quest. questLevels = 0,1,2 /// @notice Sends U_Us (max. 5) on a quest, U_Us of the same clan and if rare will get a bonus multiplier! function startQuest(uint256[] memory unicornIds, uint256 questLevel) public { require( areOwned(unicornIds), "UniQuest: One or More Unicorns are not owned by you!" ); require(questLevel <= 2, "UniQuest: Invalid Quest Level!"); require(unicornIds.length <= 5, "UniQuest: Maximum of 5 U_U only!"); require(unicornIds.length > 0, "UniQuest: At least 1 U_U required!"); _questId.increment(); _lockTokens(unicornIds); for (uint256 i = 0; i < unicornIds.length; i++) { onQuest[unicornIds[i]] = _questId.current(); } uint256 _clanMultiplier; uint256 _rareMultiplier; (_clanMultiplier, _rareMultiplier) = calculateMultipliers(unicornIds); Quest memory _quest = Quest( msg.sender, // address questOwner questLevel, // uint256 questLevel; block.timestamp, // uint256 questStart; block.timestamp.add(questLengths[questLevel]), // uint256 questEnd; block.timestamp, // uint256 lastClaim; _clanMultiplier, // uint256 clanMultiplier; _rareMultiplier, // uint256 rareMultiplier; lengthMultipliers[questLevel], // uint256 lengthMultiplier; unicornIds, // uint256[] unicornIds; QuestState.IN_PROGRESS // QuestState questState; ); quests[_questId.current()] = _quest; userQuests[msg.sender].push(_questId.current()); emit QuestStarted( msg.sender, _questId.current(), unicornIds, questLevel, block.timestamp, block.timestamp.add(questLengths[questLevel]) ); } /// @dev Start quest. questLevels = 0,1,2 /// @notice Sends U_Us (max. 5) on a quest, U_Us of the same clan and if rare will get a bonus multiplier! function upgradeQuest(uint256 questId, uint256 questLevel) public { Quest storage quest = quests[questId]; require( quest.questOwner == msg.sender, "UniQuest: Quest not owned by you!" ); require(questLevel <= 2, "UniQuest: Invalid Quest Level!"); require( questLevel > quest.questLevel, "UniQuest: Invalid Quest Level!" ); // Increase Lockup Duration quest.questLevel = questLevel; quest.questEnd = block.timestamp + questLengths[questLevel]; quest.lengthMultiplier = lengthMultipliers[questLevel]; } /// @dev Claim UCD reward for given quest function claimRewards(uint256 questId) public nonReentrant { Quest storage quest = quests[questId]; address questOwner = quest.questOwner; require( msg.sender == questOwner, "UniQuest: Only quest owner can claim candy" ); require( quest.questState == QuestState.IN_PROGRESS, "UniQuest: Quest has already ended!" ); uint256 rewards = calculateRewards(questId); UCD.mint(questOwner, rewards); quest.lastClaim = block.timestamp; emit RewardClaimed(msg.sender, rewards, block.timestamp); } /// @dev QOL to claim all rewards function claimAllRewards() public nonReentrant { uint256[] memory questIds = getUserQuests(msg.sender); uint256 totalRewards = 0; Quest storage quest; for (uint256 i = 0; i < questIds.length; i++) { totalRewards = totalRewards.add(calculateRewards(questIds[i])); quest = quests[questIds[i]]; quest.lastClaim = block.timestamp; } UCD.mint(msg.sender, totalRewards); } /// @dev Claim HODLing Rewards for owned pure U_Us /// @notice You can only claim HODL rewards for your owned pure U_Us function claimHODLRewards(uint256[] memory tokenIds) public nonReentrant { for (uint256 i = 0; i < tokenIds.length; i++) { require( UU.ownerOf(tokenIds[i]) == msg.sender, "UniQuest: Not Owner of token" ); } uint256 rewards = calculateHODLRewards(tokenIds); for (uint256 i = 0; i < tokenIds.length; i++) { HODLLastClaim[tokenIds[i]] = block.timestamp; } UCD.mint(msg.sender, rewards); } /// @dev Claim tokens and leave quest /// @notice End quest for U_Us. You will stop acumulating UCD. function endQuest(uint256 questId) public { // Only Quest Owner require( msg.sender == quests[questId].questOwner, "UniQuest: Not the owner of quest" ); // Current Time > Quest End Time require( isQuestEndable(questId), "UniQuest: Unicorns are still questing!" ); // Must be questing state require( quests[questId].questState == QuestState.IN_PROGRESS, "UniQuest: Quest already Ended" ); // Distribute Remaining Rewards claimRewards(questId); // Unlock Tokens _unlockTokens(quests[questId].unicornIds); // Change Quest State such that further claims cannot be made quests[questId].questState = QuestState.ENDED; emit QuestEnded(msg.sender, questId, block.timestamp); } // ----------------------- View FUNCTIONS ----------------------- /// @dev Determines if quest is ended function isQuestEndable(uint256 questId) public view returns (bool) { return block.timestamp > quests[questId].questEnd; } /// @dev Retrieves clan multiplier function getClanMultiplier(uint256 clanCount) public view returns (uint256) { return clanMultipliers[clanCount]; } /// @dev Retrieves Rare multiplier function getRareMultiplier(uint256 rareCount) public view returns (uint256) { return rareMultipliers[rareCount]; } /// @dev Retrieves Length multiplier function getLengthMultiplier(uint256 questLevel) public view returns (uint256) { return lengthMultipliers[questLevel]; } /// @dev Calculates Clan Multiplier based on tokenIds function calculateMultipliers(uint256[] memory _tokenIds) internal view returns (uint256 _clanMultiplier, uint256 _rareMultiplier) { uint8[6] memory _clanCounter = [0, 0, 0, 0, 0, 0]; uint8 maxCount = 0; uint8 maxIndex; uint256 rareCount = 0; // Count UU per clan for (uint8 i = 0; i < _tokenIds.length; i++) { _clanCounter[getClan(_tokenIds[i]) - 1] += 1; } // Find Maximum Count and Index of Max Count for (uint8 i = 0; i < _clanCounter.length; i++) { if (_clanCounter[i] > maxCount) { maxCount = _clanCounter[i]; maxIndex = i; } } // Wildcard bonus if (maxIndex < 4) { maxCount += _clanCounter[5]; } _clanMultiplier = getClanMultiplier(maxCount); rareCount = rareCount.add(_clanCounter[4]).add(_clanCounter[5]); _rareMultiplier = getRareMultiplier(rareCount); } /// @dev Calulate HODLing rewards for tokenIds given function calculateHODLRewards(uint256[] memory tokenIds) public view returns (uint256 HODLRewards) { HODLRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { if (isGoldenUni[tokenIds[i]]) { HODLRewards = HODLRewards.add( baseGoldenReward.mul(calcGoldenDuration(tokenIds[i])).div( timescale ) ); } else if (isRoboUni[tokenIds[i]]) { HODLRewards = HODLRewards.add( baseRoboReward.mul(calcRoboDuration(tokenIds[i])).div( timescale ) ); } } } /// @dev Calculate duration since last claim for golden U_Us function calcGoldenDuration(uint256 tokenId) private view returns (uint256) { return block.timestamp.sub(HODLLastClaim[tokenId]); } /// @dev Calculate duration since last claim for UniMech U_Us function calcRoboDuration(uint256 tokenId) private view returns (uint256) { return block.timestamp.sub(HODLLastClaim[tokenId]); } /// @dev Caluclate rewards for given Quest Id function calculateRewards(uint256 questId) public view returns (uint256 rewardAmount) { Quest memory quest = quests[questId]; rewardAmount = baseReward .mul(block.timestamp.sub(quest.lastClaim)) .mul(quest.unicornIds.length) .mul(quest.clanMultiplier) .mul(quest.rareMultiplier) .mul(quest.lengthMultiplier) .div(timescale) .div(1000000000000); } /// @dev Determines if the tokenIds are availiable for questing function areAvailiable(uint256[] memory tokenIds) public view returns (bool out) { out = true; for (uint256 i = 0; i < tokenIds.length; i++) { if (onQuest[tokenIds[i]] > 0) { out = false; } } } /// @dev Determines if the all tokenIds are owned by msg sneder function areOwned(uint256[] memory tokenIds) public view returns (bool out) { out = true; for (uint256 i = 0; i < tokenIds.length; i++) { if (UU.ownerOf(tokenIds[i]) != msg.sender) { out = false; } } } function getUserQuests(address user) public view returns (uint256[] memory) { return userQuests[user]; } function getQuest(uint256 questId) public view returns (Quest memory) { return quests[questId]; } function isQuestOver(uint256 questId) public view returns (bool) { Quest memory quest = quests[questId]; return block.timestamp > quest.questEnd; } function getClan(uint256 tokenId) public view returns (uint8) { return uint8(clans[tokenId - 1]); } // ---------------------- ADMIN FUNCTIONS ----------------------- function setBaseReward(uint256 _amount) public onlyAdmin { baseReward = _amount; } function setRoboReward(uint256 _amount) public onlyAdmin { baseRoboReward = _amount; } function setGoldenReward(uint256 _amount) public onlyAdmin { baseGoldenReward = _amount; } /// @dev Storing Clan Metadata as 1 byte hexes on a byte for gas optimization function setRoboIds(uint256[] memory _roboTokenIds) public onlyAdmin { for (uint256 i = 0; i < _roboTokenIds.length; i++) { isRoboUni[_roboTokenIds[i]] = true; HODLLastClaim[_roboTokenIds[i]] = block.timestamp; } } /// @dev Storing Clan Metadata as 1 byte hexes on a byte for gas optimization function setGoldenIds(uint256[] memory _goldenTokenIds) public onlyAdmin { for (uint256 i = 0; i < _goldenTokenIds.length; i++) { isGoldenUni[_goldenTokenIds[i]] = true; HODLLastClaim[_goldenTokenIds[i]] = block.timestamp; } } /// @dev Storing Clan Metadata as 1 byte hexes on a byte for gas optimization function updateClans(bytes calldata _clans) public onlyAdmin { clans = _clans; } function setUniCandy(address uniCandy) public onlyAdmin { UCD = ICandyToken(uniCandy); } function setTimeScale(uint256 _newTimescale) public onlyAdmin { timescale = _newTimescale; } function transferQuestOwnership(uint256 questId, address newOwner) public onlyAdmin { Quest storage quest = quests[questId]; quest.questOwner = newOwner; } function setQuestLengths(uint256[] memory _newQuestLengths) public onlyAdmin { questLengths = _newQuestLengths; } function _lockTokens(uint256[] memory tokenIds) private { for (uint256 i; i < tokenIds.length; i++) { UU.safeTransferFrom(msg.sender, address(this), tokenIds[i]); } } function _unlockTokens(uint256[] memory tokenIds) private { for (uint256 i; i < tokenIds.length; i++) { UU.safeTransferFrom(address(this), msg.sender, tokenIds[i]); // reset last claim for HODL rewards HODLLastClaim[tokenIds[i]] = block.timestamp; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ICandyToken is IERC20 { function updateRewardOnMint(address _user, uint256 _amount) external; function updateReward(address _from, address _to) external; function getReward(address _to) external; function burn(address _from, uint256 _amount) external; function mint(address to, uint256 amount) external; function getTotalClaimable(address _user) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; interface IUninterestedUnicorns is IERC721 { function mint(uint256 _quantity) external payable; function getPrice(uint256 _quantity) external view returns (uint256); function totalSupply() external view returns (uint256); function lockTokens(uint8[] memory tokenId) external; function unlockTokens(uint8[] memory tokenId) external; }
@dev Calculates Clan Multiplier based on tokenIds Count UU per clan Find Maximum Count and Index of Max Count Wildcard bonus
function calculateMultipliers(uint256[] memory _tokenIds) internal view returns (uint256 _clanMultiplier, uint256 _rareMultiplier) { uint8[6] memory _clanCounter = [0, 0, 0, 0, 0, 0]; uint8 maxCount = 0; uint8 maxIndex; uint256 rareCount = 0; for (uint8 i = 0; i < _tokenIds.length; i++) { _clanCounter[getClan(_tokenIds[i]) - 1] += 1; } for (uint8 i = 0; i < _clanCounter.length; i++) { if (_clanCounter[i] > maxCount) { maxCount = _clanCounter[i]; maxIndex = i; } } if (maxIndex < 4) { maxCount += _clanCounter[5]; } _clanMultiplier = getClanMultiplier(maxCount); rareCount = rareCount.add(_clanCounter[4]).add(_clanCounter[5]); _rareMultiplier = getRareMultiplier(rareCount); }
11,955,290
[ 1, 10587, 3905, 304, 5991, 5742, 2511, 603, 1147, 2673, 6974, 587, 57, 1534, 927, 304, 4163, 18848, 6974, 471, 3340, 434, 4238, 6974, 23049, 324, 22889, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 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, 4604, 5002, 8127, 414, 12, 11890, 5034, 8526, 3778, 389, 2316, 2673, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 389, 830, 304, 23365, 16, 2254, 5034, 389, 354, 266, 23365, 13, 203, 565, 288, 203, 3639, 2254, 28, 63, 26, 65, 3778, 389, 830, 304, 4789, 273, 306, 20, 16, 374, 16, 374, 16, 374, 16, 374, 16, 374, 15533, 203, 3639, 2254, 28, 943, 1380, 273, 374, 31, 203, 3639, 2254, 28, 30764, 31, 203, 3639, 2254, 5034, 25671, 1380, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 389, 2316, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 389, 830, 304, 4789, 63, 588, 2009, 304, 24899, 2316, 2673, 63, 77, 5717, 300, 404, 65, 1011, 404, 31, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 389, 830, 304, 4789, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 67, 830, 304, 4789, 63, 77, 65, 405, 943, 1380, 13, 288, 203, 7734, 943, 1380, 273, 389, 830, 304, 4789, 63, 77, 15533, 203, 7734, 30764, 273, 277, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 1896, 1016, 411, 1059, 13, 288, 203, 5411, 943, 1380, 1011, 389, 830, 304, 4789, 63, 25, 15533, 203, 3639, 289, 203, 203, 3639, 389, 830, 304, 23365, 273, 1927, 6115, 23365, 12, 1896, 1380, 1769, 203, 203, 3639, 25671, 1380, 273, 25671, 1380, 18, 1289, 24899, 2 ]
pragma solidity ^0.4.24; contract PriceOracleInterface { /** * @notice Gets the price of a given asset * @dev fetches the price of a given asset * @param asset Asset to get the price of * @return the price scaled by 10**18, or zero if the price is not available */ function assetPrices(address asset) public view returns (uint); } contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE } /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(Error.OPAQUE_ERROR), uint(info), opaqueError); return uint(Error.OPAQUE_ERROR); } } contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate(address asset, uint cash, uint borrows) public view returns (uint, uint); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate(address asset, uint cash, uint borrows) public view returns (uint, uint); } contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint a, uint b) internal pure returns (Error, uint) { if (a == 0) { return (Error.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (Error, uint) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (Error, uint) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint a, uint b) internal pure returns (Error, uint) { uint c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub(uint a, uint b, uint c) internal pure returns (Error, uint) { (Error err0, uint sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn(address asset, address from, uint amount) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address asset, address from, uint amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address asset, address to, uint amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } contract Exponential is ErrorReporter, CarefulMath { // TODO: We may wish to put the result of 10**18 here instead of the expression. // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint constant expScale = 10**18; // See TODO on expScale uint constant halfExpScale = expScale/2; struct Exp { uint mantissa; } uint constant mantissaOne = 10**18; uint constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (Error, Exp memory) { (Error err0, uint scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error error, uint result) = add(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error error, uint result) = sub(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) { (Error err0, uint scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) { (Error err0, uint descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp divisor) pure internal returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error err0, uint doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint doubleScaledProductWithHalfScale) = add(halfExpScale, doubleScaledProduct); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint product) = div(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / 10**18; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo. } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract MoneyMarket is Exponential, SafeToken { uint constant initialInterestIndex = 10 ** 18; uint constant defaultOriginationFee = 0; // default is zero bps uint constant minimumCollateralRatioMantissa = 11 * (10 ** 17); // 1.1 uint constant maximumLiquidationDiscountMantissa = (10 ** 17); // 0.1 /** * @notice `MoneyMarket` is the core Compound MoneyMarket contract */ constructor() public { admin = msg.sender; collateralRatio = Exp({mantissa: 2 * mantissaOne}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: 0}); // oracle must be configured via _setOracle } /** * @notice Do not pay directly into MoneyMarket, please use `supply`. */ function() payable public { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address public oracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = the total interestIndex as calculated after applying the customer's most recent balance-changing action * } */ struct Balance { uint principal; uint interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint blockNumber; InterestRateModel interestRateModel; uint totalSupply; uint supplyRateMantissa; uint supplyIndex; uint totalBorrows; uint borrowRateMantissa; uint borrowIndex; } /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken(address account, address asset, uint amount, uint startingBalance, uint borrowAmountWithFee, uint newBalance); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) */ event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter, address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter); /** * @dev emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @dev newOracle - address of new oracle */ event NewOracle(address oldOracle, address newOracle); /** * @dev emitted when new market is supported by admin */ event SupportedMarket(address asset, address interestRateModel); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters(uint oldCollateralRatioMantissa, uint newCollateralRatioMantissa, uint oldLiquidationDiscountMantissa, uint newLiquidationDiscountMantissa); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee(uint oldOriginationFeeMantissa, uint newOriginationFeeMantissa); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel(address asset, address interestRateModel); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner); /** * @dev emitted when a supported market is suspended by admin */ event SuspendedMarket(address asset); /** * @dev emitted when admin either pauses or resumes the contract; newState is the resulting state */ event SetPaused(bool newState); /** * @dev Simple function to calculate min between two numbers. */ function min(uint a, uint b) pure internal returns (uint) { if (a < b) { return a; } else { return b; } } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint) { return collateralMarkets.length; } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` */ function calculateInterestIndex(uint startingInterestIndex, uint interestRateMantissa, uint blockStart, uint blockEnd) pure internal returns (Error, uint) { // Get the block delta (Error err0, uint blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar(Exp({mantissa: interestRateMantissa}), blockDelta); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp(blocksTimesRate, Exp({mantissa: mantissaOne})); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar(onePlusBlocksTimesRate, startingInterestIndex); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * * TODO: Is there a way to handle this that is less likely to overflow? */ function calculateBalance(uint startingBalance, uint interestIndexStart, uint interestIndexEnd) pure internal returns (Error, uint) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint balanceTimesIndex) = mul(startingBalance, interestIndexEnd); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. */ function getPriceForAssetAmount(address asset, uint assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` */ function getPriceForAssetAmountMulCollatRatio(address asset, uint assetAmount) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * * TODO: Track at what magnitude this fee rounds down to zero? */ function calculateBorrowAmountWithFee(uint borrowAmount) view internal returns (Error, uint) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp(originationFee, Exp({mantissa: mantissaOne})); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar(originationFeeFactor, borrowAmount); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (oracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } PriceOracleInterface oracleInterface = PriceOracleInterface(oracle); uint priceMantissa = oracleInterface.assetPrices(asset); return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) * * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address? */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller = pendingAdmin // msg.sender can't be zero if (msg.sender != pendingAdmin) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint(Error.NO_ERROR); } /** * @notice Set new oracle, who can set asset prices * @dev Admin function to change oracle * @param newOracle New oracle address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setOracle(address newOracle) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORACLE_OWNER_CHECK); } // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. PriceOracleInterface oracleInterface = PriceOracleInterface(newOracle); oracleInterface.assetPrices(address(0)); address oldOracle = oracle; // Store oracle = newOracle oracle = newOracle; emit NewOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice set `paused` to the specified state * @dev Admin function to pause or resume the market * @param requestedState value to assign to `paused` * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPaused(bool requestedState) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSED_OWNER_CHECK); } paused = requestedState; emit SetPaused(requestedState); return uint(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int) { (Error err, Exp memory accountLiquidity, Exp memory accountShortfall) = calculateAccountLiquidity(account); require(err == Error.NO_ERROR); if (isZeroExp(accountLiquidity)) { return -1 * int(truncate(accountShortfall)); } else { return int(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) view public returns (uint) { Error err; uint newSupplyIndex; uint userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); require(err == Error.NO_ERROR); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex); require(err == Error.NO_ERROR); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) view public returns (uint) { Error err; uint newBorrowIndex; uint userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); require(err == Error.NO_ERROR); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex); require(err == Error.NO_ERROR); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use with Compound * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail(Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use with Compound. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUSPEND_MARKET_OWNER_CHECK); } // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; emit SuspendedMarket(asset); return uint(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters(uint collateralRatioMantissa, uint liquidationDiscountMantissa) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RISK_PARAMETERS_OWNER_CHECK); } Exp memory newCollateralRatio = Exp({mantissa: collateralRatioMantissa}); Exp memory newLiquidationDiscount = Exp({mantissa: liquidationDiscountMantissa}); Exp memory minimumCollateralRatio = Exp({mantissa: minimumCollateralRatioMantissa}); Exp memory maximumLiquidationDiscount = Exp({mantissa: maximumLiquidationDiscountMantissa}); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail(Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail(Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp(newLiquidationDiscount, Exp({mantissa: mantissaOne})); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if (lessThanOrEqualExp(newCollateralRatio, newLiquidationDiscountPlusOne)) { return fail(Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters(oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the origination fee (which is a multiplier on new borrows) * @dev Owner function to set the origination fee * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setOriginationFee(uint originationFeeMantissa) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORIGINATION_FEE_OWNER_CHECK); } // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee(oldOriginationFee.mantissa, originationFeeMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity= cash - (supply + borrows) * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash - (supply + borrows) * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint amount) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK); } // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint cash = getCash(asset); (Error err0, uint equity) = addThenSub(cash, markets[asset].totalBorrows, markets[asset].totalSupply); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail(Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED); } //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint(Error.NO_ERROR); // success } /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint startingBalance; uint newSupplyIndex; uint userSupplyCurrent; uint userSupplyUpdated; uint newTotalSupply; uint currentCash; uint updatedCash; uint newSupplyRateMantissa; uint newBorrowIndex; uint newBorrowRateMantissa; } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { return fail(Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED); } // Fail gracefully if asset is not approved or has insufficient balance err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (err, localResults.userSupplyCurrent) = calculateBalance(balance.principal, balance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED); } (err, localResults.userSupplyUpdated) = add(localResults.userSupplyCurrent, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, balance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; emit SupplyReceived(msg.sender, asset, amount, localResults.startingBalance, localResults.userSupplyUpdated); return uint(Error.NO_ERROR); // success } struct WithdrawLocalVars { uint withdrawAmount; uint startingBalance; uint newSupplyIndex; uint userSupplyCurrent; uint userSupplyUpdated; uint newTotalSupply; uint currentCash; uint updatedCash; uint newSupplyRateMantissa; uint newBorrowIndex; uint newBorrowRateMantissa; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; uint withdrawCapacity; } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint requestedAmount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED); } Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. (err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue(asset, localResults.accountLiquidity); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min(localResults.withdrawCapacity, localResults.userSupplyCurrent); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub(localResults.currentCash, localResults.withdrawAmount); if (err != Error.NO_ERROR) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub(localResults.userSupplyCurrent, localResults.withdrawAmount); if (err != Error.NO_ERROR) { return fail(Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(asset, localResults.withdrawAmount); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfWithdrawal) ) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; emit SupplyWithdrawn(msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, localResults.userSupplyUpdated); return uint(Error.NO_ERROR); // success } struct AccountValueLocalVars { address assetAddress; uint collateralMarketsLength; uint newSupplyIndex; uint userSupplyCurrent; Exp supplyTotalValue; Exp sumSupplies; uint newBorrowIndex; uint userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). */ function calculateAccountLiquidity(address userAddress) internal view returns (Error, Exp memory, Exp memory) { Error err; uint sumSupplyValuesMantissa; uint sumBorrowValuesMantissa; (err, sumSupplyValuesMantissa, sumBorrowValuesMantissa) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return(err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({mantissa: sumSupplyValuesMantissa}); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp(collateralRatio, Exp({mantissa: sumBorrowValuesMantissa})); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) * TODO: Possibly should add a Min(500, collateralMarkets.length) for extra safety * TODO: To help save gas we could think about using the current Market.interestIndex * accumulate interest rather than calculating it */ function calculateAccountValuesInternal(address userAddress) internal view returns (Error, uint, uint) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][localResults.assetAddress]; Balance storage borrowBalance = borrowBalances[userAddress][localResults.assetAddress]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex(currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); } (err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return (err, 0, 0); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userSupplyCurrent); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp(localResults.supplyTotalValue, localResults.sumSupplies); if (err != Error.NO_ERROR) { return (err, 0, 0); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex(currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return (err, 0, 0); } // In the case of borrow, we multiply the borrow value by the collateral ratio (err, localResults.borrowTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userBorrowCurrent); // ( borrowCurrent* oraclePrice * collateralRatio) = borrowTotalValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp(localResults.borrowTotalValue, localResults.sumBorrows); if (err != Error.NO_ERROR) { return (err, 0, 0); } } } return (Error.NO_ERROR, localResults.sumSupplies.mantissa, localResults.sumBorrows.mantissa); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns (uint, uint, uint) { (Error err, uint supplyValue, uint borrowValue) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint(err), 0, 0); } return (0, supplyValue, borrowValue); } struct PayBorrowLocalVars { uint newBorrowIndex; uint userBorrowCurrent; uint repayAmount; uint userBorrowUpdated; uint newTotalBorrows; uint currentCash; uint updatedCash; uint newSupplyIndex; uint newSupplyRateMantissa; uint newBorrowRateMantissa; uint startingBalance; } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED); } PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (amount == uint(-1)) { localResults.repayAmount = min(getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent); } else { localResults.repayAmount = amount; } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub(localResults.userBorrowCurrent, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub(market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; emit BorrowRepaid(msg.sender, asset, localResults.repayAmount, localResults.startingBalance, localResults.userBorrowUpdated); return uint(Error.NO_ERROR); // success } struct BorrowLocalVars { uint newBorrowIndex; uint userBorrowCurrent; uint borrowAmountWithFee; uint userBorrowUpdated; uint newTotalBorrows; uint currentCash; uint updatedCash; uint newSupplyIndex; uint newSupplyRateMantissa; uint newBorrowRateMantissa; uint startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint newBorrowIndex_UnderwaterAsset; uint newSupplyIndex_UnderwaterAsset; uint newBorrowIndex_CollateralAsset; uint newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint updatedBorrowBalance_TargetUnderwaterAsset; uint newTotalBorrows_ProtocolUnderwaterAsset; uint startingBorrowBalance_TargetUnderwaterAsset; uint startingSupplyBalance_TargetCollateralAsset; uint startingSupplyBalance_LiquidatorCollateralAsset; uint currentSupplyBalance_TargetCollateralAsset; uint updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint updatedSupplyBalance_LiquidatorCollateralAsset; uint newTotalSupply_ProtocolCollateralAsset; uint currentCash_ProtocolUnderwaterAsset; uint updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint newSupplyRateMantissa_ProtocolUnderwaterAsset; uint newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint discountedBorrowDenominatedCollateral; uint maxCloseableBorrowAmount_TargetUnderwaterAsset; uint closeBorrowAmount_TargetUnderwaterAsset; uint seizeSupplyAmount_TargetCollateralAsset; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address targetAccount, address assetBorrow, address assetCollateral, uint requestedAmountClose) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED); } LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[targetAccount][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[targetAccount][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if(err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset (err, localResults.newBorrowIndex_UnderwaterAsset) = calculateInterestIndex(borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET); } (err, localResults.currentBorrowBalance_TargetUnderwaterAsset) = calculateBalance(borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset (err, localResults.newSupplyIndex_CollateralAsset) = calculateInterestIndex(collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET); } (err, localResults.currentSupplyBalance_TargetCollateralAsset) = calculateBalance(supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset (err, localResults.currentSupplyBalance_LiquidatorCollateralAsset) = calculateBalance(supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (err, localResults.discountedBorrowDenominatedCollateral) = calculateDiscountedBorrowDenominatedCollateral(localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. (err, localResults.discountedRepayToEvenAmount) = calculateDiscountedRepayToEvenAmount(targetAccount, localResults.underwaterAssetPrice); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (requestedAmountClose == uint(-1)) { localResults.closeBorrowAmount_TargetUnderwaterAsset = localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if (localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset) { return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) (err, localResults.seizeSupplyAmount_TargetCollateralAsset) = calculateAmountSeize(localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into Compound // Fail gracefully if asset is not approved or has insufficient balance err = checkTransferIn(assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows_ProtocolUnderwaterAsset) = addThenSub(borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. (err, localResults.newSupplyIndex_UnderwaterAsset) = calculateInterestIndex(borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET); } (rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset) = borrowMarket.interestRateModel.getSupplyRate(assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset) = borrowMarket.interestRateModel.getBorrowRate(assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. (err, localResults.newBorrowIndex_CollateralAsset) = calculateInterestIndex(collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert (err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset) = add(localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert (err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } // Save borrow market updates borrowMarket.blockNumber = getBlockNumber(); borrowMarket.totalBorrows = localResults.newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = getBlockNumber(); collateralMarket.totalSupply = localResults.newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults.newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults.newBorrowIndex_CollateralAsset; // Save user updates localResults.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset.principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults.updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults.newBorrowIndex_UnderwaterAsset; localResults.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset.principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults.updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults.newSupplyIndex_CollateralAsset; localResults.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset.principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults.updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults.newSupplyIndex_CollateralAsset; emitLiquidationEvent(localResults); return uint(Error.NO_ERROR); // success } /** * @dev this function exists to avoid error `CompilerError: Stack too deep, try removing local variables.` in `liquidateBorrow` */ function emitLiquidationEvent(LiquidateLocalVars memory localResults) internal { // event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter, // address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter); emit BorrowLiquidated(localResults.targetAccount, localResults.assetBorrow, localResults.startingBorrowBalance_TargetUnderwaterAsset, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.updatedBorrowBalance_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.startingSupplyBalance_TargetCollateralAsset, localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset, localResults.updatedSupplyBalance_TargetCollateralAsset); } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. **/ function calculateDiscountedRepayToEvenAmount(address targetAccount, Exp memory underwaterAssetPrice) internal view returns (Error, uint) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio (err, _accountLiquidity, accountShortfall_TargetUser) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp(collateralRatio, liquidationDiscount); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp(collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne})); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp(underwaterAssetPrice, discountedCollateralRatioMinusOne); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); (err, rawResult) = divExp(accountShortfall_TargetUser, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) */ function calculateDiscountedBorrowDenominatedCollateral(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint supplyCurrent_TargetCollateralAsset) view internal returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar(collateralPrice, supplyCurrent_TargetCollateralAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(onePlusLiquidationDiscount, underwaterAssetPrice); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral **/ function calculateAmountSeize(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint closeBorrowAmount_TargetUnderwaterAsset) internal view returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(underwaterAssetPrice, liquidationMultiplier); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar(priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail(Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED); } // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add(localResults.userBorrowCurrent, localResults.borrowAmountWithFee); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub(market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED); } // Check customer liquidity (err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` (err, localResults.ethValueOfBorrowAmountWithFee) = getPriceForAssetAmountMulCollatRatio(asset, localResults.borrowAmountWithFee); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; emit BorrowTaken(msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, localResults.userBorrowUpdated); return uint(Error.NO_ERROR); // success } }
* @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] (Oracle price for the collateral / Oracle price for the borrow)/ To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ]
function calculateDiscountedBorrowDenominatedCollateral(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint supplyCurrent_TargetCollateralAsset) view internal returns (Error, uint) { Error err; Exp memory rawResult; if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar(collateralPrice, supplyCurrent_TargetCollateralAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(onePlusLiquidationDiscount, underwaterAssetPrice); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); }
2,476,838
[ 1, 23650, 329, 38, 15318, 8517, 362, 7458, 13535, 2045, 287, 273, 306, 2859, 1283, 3935, 342, 261, 21, 397, 4501, 26595, 367, 9866, 25887, 225, 261, 23601, 6205, 364, 326, 4508, 2045, 287, 342, 28544, 6205, 364, 326, 29759, 13176, 2974, 4543, 13885, 8296, 16, 732, 283, 17, 1019, 471, 1041, 326, 5295, 1427, 732, 741, 404, 16536, 471, 1338, 622, 326, 679, 306, 2859, 1283, 3935, 225, 261, 23601, 6205, 364, 326, 4508, 2045, 287, 25887, 342, 306, 261, 21, 397, 4501, 26595, 367, 9866, 13, 225, 261, 23601, 6205, 364, 326, 29759, 13, 308, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 9866, 329, 38, 15318, 8517, 362, 7458, 13535, 2045, 287, 12, 2966, 3778, 3613, 91, 2045, 6672, 5147, 16, 7784, 3778, 4508, 2045, 287, 5147, 16, 2254, 14467, 3935, 67, 2326, 13535, 2045, 287, 6672, 13, 1476, 2713, 1135, 261, 668, 16, 2254, 13, 288, 203, 3639, 1068, 393, 31, 203, 3639, 7784, 3778, 1831, 1253, 31, 203, 203, 3639, 309, 261, 370, 480, 1068, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 261, 370, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 261, 370, 16, 14467, 3935, 10694, 23601, 13535, 2045, 287, 13, 273, 14064, 13639, 12, 12910, 2045, 287, 5147, 16, 14467, 3935, 67, 2326, 13535, 2045, 287, 6672, 1769, 203, 3639, 309, 261, 370, 480, 1068, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 261, 370, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 261, 370, 16, 1245, 13207, 48, 18988, 350, 367, 9866, 10694, 23601, 38, 15318, 13, 273, 14064, 2966, 12, 476, 13207, 48, 18988, 350, 367, 9866, 16, 3613, 91, 2045, 6672, 5147, 1769, 203, 3639, 309, 261, 370, 480, 1068, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 261, 370, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 261, 370, 16, 1831, 1253, 13, 273, 3739, 2966, 12, 2859, 1283, 3935, 10694, 23601, 13535, 2045, 287, 16, 1245, 13207, 48, 18988, 350, 367, 9866, 10694, 23601, 38, 15318, 1769, 203, 3639, 309, 261, 370, 480, 1068, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 261, 370, 16, 2 ]
pragma solidity >=0.5.0; // This contract is used to emulate currency transfer destination contract, it can accept incoming transfer via fallback function or emulate crash in function doCrash(). contract CrashContract { // State variable storing the number of times fallback function was called. uint fallbackCounter = 0; // Fallback function. fallback() external payable { fallbackCounter += 1; } receive() external payable { fallbackCounter += 1; } // Function to obtain fallback counter function getCounter() public view returns (uint) { tvm.accept(); return fallbackCounter; } // Function that crashes after call. function doCrash() public payable { require(false, 73); } }
Function to obtain fallback counter
function getCounter() public view returns (uint) { tvm.accept(); return fallbackCounter; }
15,796,440
[ 1, 2083, 358, 7161, 5922, 3895, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 31107, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 202, 202, 88, 3489, 18, 9436, 5621, 203, 202, 202, 2463, 5922, 4789, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xaf24BFD866860800121d4268aEEC90357C3e0cc4/sources/contracts/compound/CarefulMath.sol
* @title Careful Math @author Compound @notice Derived from OpenZeppelin's SafeMath library/
contract CarefulMath { pragma solidity ^0.6.8; enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); return (MathError.NO_ERROR, c); } } function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); return (MathError.NO_ERROR, c); } } function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); return (MathError.NO_ERROR, c); } } } else { function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); return (MathError.INTEGER_UNDERFLOW, 0); } } function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); return (MathError.INTEGER_UNDERFLOW, 0); } } } else { function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); return (MathError.INTEGER_OVERFLOW, 0); } } function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); return (MathError.INTEGER_OVERFLOW, 0); } } } else { function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }
14,259,424
[ 1, 39, 834, 2706, 2361, 225, 21327, 225, 14969, 2950, 628, 3502, 62, 881, 84, 292, 267, 1807, 14060, 10477, 5313, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 385, 834, 2706, 10477, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 28, 31, 203, 565, 2792, 2361, 668, 288, 203, 3639, 3741, 67, 3589, 16, 203, 3639, 3690, 25216, 67, 6486, 67, 24968, 16, 203, 3639, 16481, 67, 12959, 17430, 16, 203, 3639, 16481, 67, 31625, 17430, 203, 565, 289, 203, 203, 565, 445, 14064, 14342, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 10477, 668, 16, 2254, 5034, 13, 203, 565, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 261, 10477, 668, 18, 3417, 67, 3589, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 203, 3639, 309, 261, 71, 342, 279, 480, 324, 13, 288, 203, 5411, 327, 261, 10477, 668, 18, 14217, 67, 12959, 17430, 16, 374, 1769, 203, 5411, 327, 261, 10477, 668, 18, 3417, 67, 3589, 16, 276, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 14064, 14342, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 10477, 668, 16, 2254, 5034, 13, 203, 565, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 261, 10477, 668, 18, 3417, 67, 3589, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 203, 3639, 309, 261, 71, 342, 279, 480, 324, 13, 288, 203, 5411, 2 ]
./full_match/1/0xE980EC62378529D95Ba446433F4DEB6324129c59/sources/lib/royalty-guard/src/royalty-guard/RoyaltyGuard.sol
@title RoyaltyGuard @author highland, koloz, van arman @notice An abstract contract with the necessary functions, structures, modifiers to ensure royalties are paid. @dev Inherriting this contract requires implementing {hasAdminPermission} and connecting the desired functions to the {checkList} modifier.
abstract contract RoyaltyGuard is IRoyaltyGuard, ERC165 { using EnumerableSet for EnumerableSet.AddressSet; Private Contract Storage mapping(IRoyaltyGuard.ListType => EnumerableSet.AddressSet) private list; IRoyaltyGuard.ListType private listType; Modifiers pragma solidity 0.8.15; import {IRoyaltyGuard} from "./IRoyaltyGuard.sol"; import {EnumerableSet} from "openzeppelin-contracts/utils/structs/EnumerableSet.sol"; import {ERC165} from "openzeppelin-contracts/utils/introspection/ERC165.sol"; modifier checkList(address _addr) { if (listType == IRoyaltyGuard.ListType.ALLOW) { if (!list[IRoyaltyGuard.ListType.ALLOW].contains(_addr)) revert IRoyaltyGuard.Unauthorized(); if (list[IRoyaltyGuard.ListType.DENY].contains(_addr)) revert IRoyaltyGuard.Unauthorized(); } _; } modifier checkList(address _addr) { if (listType == IRoyaltyGuard.ListType.ALLOW) { if (!list[IRoyaltyGuard.ListType.ALLOW].contains(_addr)) revert IRoyaltyGuard.Unauthorized(); if (list[IRoyaltyGuard.ListType.DENY].contains(_addr)) revert IRoyaltyGuard.Unauthorized(); } _; } } else if (listType == IRoyaltyGuard.ListType.DENY) { modifier onlyAdmin() { if (!hasAdminPermission(msg.sender)) revert IRoyaltyGuard.MustBeAdmin(); _; } Admin Functions function toggleListType(IRoyaltyGuard.ListType _newListType) external virtual onlyAdmin { _setListType(_newListType); } function batchAddAddressToRoyaltyList(IRoyaltyGuard.ListType _listType, address[] calldata _addrs) external virtual onlyAdmin { if (_listType == IRoyaltyGuard.ListType.OFF) revert IRoyaltyGuard.CantAddToOFFList(); _batchUpdateList(_listType, _addrs, true); } function batchRemoveAddressToRoyaltyList(IRoyaltyGuard.ListType _listType, address[] calldata _addrs) external virtual onlyAdmin { _batchUpdateList(_listType, _addrs, false); } function clearList(IRoyaltyGuard.ListType _listType) external virtual onlyAdmin { delete list[_listType]; emit ListCleared(msg.sender, _listType); } Public Read Functions function getList(IRoyaltyGuard.ListType _listType) external virtual view returns (address[] memory) { return list[_listType].values(); } function getInUseList() external virtual view returns (address[] memory) { return list[listType].values(); } function isOperatorInList(address _operator) external virtual view returns (bool) { return list[listType].contains(_operator); } function getListType() external virtual view returns (IRoyaltyGuard.ListType) { return listType; } function hasAdminPermission(address _addr) public virtual view returns (bool); ERC165 Overrides function supportsInterface(bytes4 _interfaceId) public virtual view override returns (bool) { return _interfaceId == type(IRoyaltyGuard).interfaceId || super.supportsInterface(_interfaceId); } Internal Functions function _setListType(IRoyaltyGuard.ListType _newListType) internal { emit ListTypeUpdated(msg.sender, listType, _newListType); listType = _newListType; } function _batchUpdateList(IRoyaltyGuard.ListType _listType, address[] memory _addrs, bool _onList) internal { if (_listType != IRoyaltyGuard.ListType.OFF) { for (uint256 i = 0; i < _addrs.length; i++) { if (_onList) { list[_listType].add(_addrs[i]); emit AddressAddedToList(msg.sender, _addrs[i], _listType); list[_listType].remove(_addrs[i]); emit AddressRemovedList(msg.sender, _addrs[i], _listType); } } } } function _batchUpdateList(IRoyaltyGuard.ListType _listType, address[] memory _addrs, bool _onList) internal { if (_listType != IRoyaltyGuard.ListType.OFF) { for (uint256 i = 0; i < _addrs.length; i++) { if (_onList) { list[_listType].add(_addrs[i]); emit AddressAddedToList(msg.sender, _addrs[i], _listType); list[_listType].remove(_addrs[i]); emit AddressRemovedList(msg.sender, _addrs[i], _listType); } } } } function _batchUpdateList(IRoyaltyGuard.ListType _listType, address[] memory _addrs, bool _onList) internal { if (_listType != IRoyaltyGuard.ListType.OFF) { for (uint256 i = 0; i < _addrs.length; i++) { if (_onList) { list[_listType].add(_addrs[i]); emit AddressAddedToList(msg.sender, _addrs[i], _listType); list[_listType].remove(_addrs[i]); emit AddressRemovedList(msg.sender, _addrs[i], _listType); } } } } function _batchUpdateList(IRoyaltyGuard.ListType _listType, address[] memory _addrs, bool _onList) internal { if (_listType != IRoyaltyGuard.ListType.OFF) { for (uint256 i = 0; i < _addrs.length; i++) { if (_onList) { list[_listType].add(_addrs[i]); emit AddressAddedToList(msg.sender, _addrs[i], _listType); list[_listType].remove(_addrs[i]); emit AddressRemovedList(msg.sender, _addrs[i], _listType); } } } } } else { }
17,007,520
[ 1, 54, 13372, 15006, 16709, 225, 3551, 15733, 16, 417, 355, 11142, 16, 331, 304, 419, 4728, 225, 1922, 8770, 6835, 598, 326, 4573, 4186, 16, 12597, 16, 10429, 358, 3387, 721, 93, 2390, 606, 854, 30591, 18, 225, 657, 76, 16399, 310, 333, 6835, 4991, 19981, 288, 5332, 4446, 5041, 97, 471, 14244, 326, 6049, 4186, 358, 326, 288, 1893, 682, 97, 9606, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 534, 13372, 15006, 16709, 353, 15908, 13372, 15006, 16709, 16, 4232, 39, 28275, 288, 203, 225, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 203, 12900, 8726, 13456, 5235, 203, 203, 225, 2874, 12, 7937, 13372, 15006, 16709, 18, 19366, 516, 6057, 25121, 694, 18, 1887, 694, 13, 3238, 666, 31, 203, 225, 15908, 13372, 15006, 16709, 18, 19366, 3238, 666, 559, 31, 203, 203, 27573, 3431, 3383, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3600, 31, 203, 5666, 288, 7937, 13372, 15006, 16709, 97, 628, 25165, 7937, 13372, 15006, 16709, 18, 18281, 14432, 203, 5666, 288, 3572, 25121, 694, 97, 628, 315, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 19, 5471, 19, 1697, 87, 19, 3572, 25121, 694, 18, 18281, 14432, 203, 5666, 288, 654, 39, 28275, 97, 628, 315, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 19, 5471, 19, 474, 26362, 19, 654, 39, 28275, 18, 18281, 14432, 203, 225, 9606, 866, 682, 12, 2867, 389, 4793, 13, 288, 203, 565, 309, 261, 1098, 559, 422, 15908, 13372, 15006, 16709, 18, 19366, 18, 13511, 13, 288, 203, 1377, 309, 16051, 1098, 63, 7937, 13372, 15006, 16709, 18, 19366, 18, 13511, 8009, 12298, 24899, 4793, 3719, 15226, 15908, 13372, 15006, 16709, 18, 13981, 5621, 203, 1377, 309, 261, 1098, 63, 7937, 13372, 15006, 16709, 18, 19366, 18, 13296, 61, 8009, 12298, 24899, 4793, 3719, 15226, 15908, 13372, 15006, 16709, 18, 13981, 5621, 203, 565, 289, 203, 565, 389, 31, 2 ]
./full_match/44787/0x712D063ea31e2a39d1aAAbced00737f455f5Cbbb/sources/contracts/Fundraise.sol
get how many donations have been sent
function getContributorsNumber(uint campaignId) public view returns (uint) { return campaigns[campaignId].contributors; }
13,254,763
[ 1, 588, 3661, 4906, 2727, 1012, 1240, 2118, 3271, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 442, 665, 13595, 1854, 12, 11890, 8965, 548, 13, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 8965, 87, 63, 14608, 548, 8009, 26930, 13595, 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 ]
pragma solidity ^0.4.18; /** * @title SimpleERC721 * * A simple implementation of the ERC721 standard * @dev See https://github.com/ethereum/eips/issues/721 */ contract SimpleERC721 { // ----------------------------------------------------------------------------------------------------------- // ------------------------------------------------ Variables ------------------------------------------------ // ----------------------------------------------------------------------------------------------------------- uint256 public totalSupply; // Basic references mapping(uint => address) internal tokenIdToOwner; mapping(address => uint[]) internal listOfOwnerTokens; mapping(uint => uint) internal tokenIndexInOwnerArray; // Approval mapping mapping(uint => address) internal approvedAddressToTransferTokenId; // ----------------------------------------------------------------------------------------------------------- // -------------------------------------------------- Events ------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // ----------------------------------------------------------------------------------------------------------- // -------------------------------------------------- Modifiers ---------------------------------------------- // ----------------------------------------------------------------------------------------------------------- modifier onlyExtantToken(uint _tokenId) { require(ownerOf(_tokenId) != address(0)); _; } modifier onlyOwnerOfToken(uint _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } // ----------------------------------------------------------------------------------------------------------- // ------------------------------------------------ View functions ------------------------------------------- // ----------------------------------------------------------------------------------------------------------- /// @dev Returns the address currently marked as the owner of _tokenID. function ownerOf(uint256 _tokenId) public view returns (address _owner) { return tokenIdToOwner[_tokenId]; } /// @dev Get the total supply of token held by this contract. function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } /// @dev Gets the balance of the specified address function balanceOf(address _owner) public view returns (uint _balance) { return listOfOwnerTokens[_owner].length; } /// @dev Gets the approved address to take ownership of a given token ID function approvedFor(uint256 _tokenId) public view returns (address _approved) { return approvedAddressToTransferTokenId[_tokenId]; } /// @dev Gets the list of tokens owned by a given address function tokensOf(address _owner) public view returns (uint256[]) { return listOfOwnerTokens[_owner]; } // ----------------------------------------------------------------------------------------------------------- // --------------------------------------------- Core Public functions --------------------------------------- // ----------------------------------------------------------------------------------------------------------- /// @dev Assigns the ownership of the NFT with ID _tokenId to _to function transfer(address _to, uint _tokenId) public onlyExtantToken (_tokenId) onlyOwnerOfToken (_tokenId) { require(_to != address(0)); _clearApprovalAndTransfer(msg.sender, _to, _tokenId); Transfer(msg.sender, _to, _tokenId); } /// @dev Grants approval for address _to to transfer the NFT with ID _tokenId. function approve(address _to, uint _tokenId) public onlyExtantToken(_tokenId) onlyOwnerOfToken (_tokenId) { require(msg.sender != _to); require(_to != address(0)); approvedAddressToTransferTokenId[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// @dev Remove approval for address _to to transfer the NFT with ID _tokenId. function removeApproval (uint _tokenId) public onlyExtantToken (_tokenId) onlyOwnerOfToken (_tokenId) { require(approvedAddressToTransferTokenId[_tokenId] != address(0)); _clearTokenApproval(_tokenId); Approval(msg.sender, address(0), _tokenId); } /// @dev transfer token From owner to _to function transferFrom(address _to, uint _tokenId) public onlyExtantToken(_tokenId) { require(approvedAddressToTransferTokenId[_tokenId] == msg.sender); require(_to != address(0)); Transfer(ownerOf(_tokenId), _to, _tokenId); _clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------- Internal functions ---------------------------------------- // ----------------------------------------------------------------------------------------------------------- // set the new token owner function _setTokenOwner(uint _tokenId, address _owner) internal { tokenIdToOwner[_tokenId] = _owner; } // add a token to the new owner list function _addTokenToOwnersList(address _owner, uint _tokenId) internal { listOfOwnerTokens[_owner].push(_tokenId); tokenIndexInOwnerArray[_tokenId] = listOfOwnerTokens[_owner].length - 1; } // remove token for the last owner list function _removeTokenFromOwnersList(address _owner, uint _tokenId) internal { uint length = listOfOwnerTokens[_owner].length; // length of owner tokens uint index = tokenIndexInOwnerArray[_tokenId]; // index of token in owner array uint swapToken = listOfOwnerTokens[_owner][length - 1]; // last token in array listOfOwnerTokens[_owner][index] = swapToken; // last token pushed to the place of the one that was transfered tokenIndexInOwnerArray[swapToken] = index; // update the index of the token we moved delete listOfOwnerTokens[_owner][length - 1]; // remove the case we emptied listOfOwnerTokens[_owner].length--; // shorten the array's length } // when the token move from one user to another, we clear the approval made by the last owner function _clearTokenApproval(uint _tokenId) internal { approvedAddressToTransferTokenId[_tokenId] = address(0); } // calls all the internal functions above, to transfer a token from one user to another function _clearApprovalAndTransfer(address _from, address _to, uint _tokenId) internal { _clearTokenApproval(_tokenId); _removeTokenFromOwnersList(_from, _tokenId); _setTokenOwner(_tokenId, _to); _addTokenToOwnersList(_to, _tokenId); } }
add a token to the new owner list
function _addTokenToOwnersList(address _owner, uint _tokenId) internal { listOfOwnerTokens[_owner].push(_tokenId); tokenIndexInOwnerArray[_tokenId] = listOfOwnerTokens[_owner].length - 1; }
1,787,516
[ 1, 1289, 279, 1147, 358, 326, 394, 3410, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1289, 1345, 774, 5460, 414, 682, 12, 2867, 389, 8443, 16, 2254, 389, 2316, 548, 13, 2713, 203, 565, 288, 203, 3639, 24692, 5541, 5157, 63, 67, 8443, 8009, 6206, 24899, 2316, 548, 1769, 203, 3639, 1147, 1016, 382, 5541, 1076, 63, 67, 2316, 548, 65, 273, 24692, 5541, 5157, 63, 67, 8443, 8009, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-31 */ // File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT /** ___ _ _ ___ _ / _ \ | | | | / (_) | | / /_\ \_ __| |_ | |/ / _ __| |___ | _ | '__| __| | \| |/ _` / __| | | | | | | |_ | |\ \ | (_| \__ \ \_| |_/_| \__| \_| \_/_|\__,_|___/ */ pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // 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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/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/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/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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // 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/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/ArtKidsOnline.sol pragma solidity ^0.8.0; contract ArtKidsOnline is ERC721Enumerable, Ownable { uint256 public constant MAX_NFT_SUPPLY = 10000; uint256 public constant BIDDING_END_TIME = 1625029200; uint256 public constant ART_KID_PRICE = 100000000000000000; uint256 public finalWinner; bool public saleStarted = false; bool public votingActive = true; event Vote(address indexed from, uint256 votedFor, uint256 votedWith); struct ArtKid { uint256 id; uint256 voteCount; address[] voters; bool hasVoted; } ArtKid[] public artKids; constructor() ERC721("Art Kids Online", "ART") { } function _baseURI() internal view virtual override returns (string memory) { return "https://api.artkids.online/"; } function getTokenURI(uint256 tokenId) public view returns (string memory) { return tokenURI(tokenId); } function backArtKid(uint256 amountToBack) public payable { require(saleStarted == true, "This sale has not started."); require(totalSupply() < MAX_NFT_SUPPLY, "The sale has ended."); require(amountToBack > 0, "You must back at least one Art Kid."); require( amountToBack <= 100, "You can only back up to 100 Art Kids at a time." ); require( totalSupply() + amountToBack <= MAX_NFT_SUPPLY, "The amount of Art Kids you are trying to back exceeds the MAX_NFT_SUPPLY." ); require(ART_KID_PRICE * amountToBack == msg.value, "Incorrect Ether value."); for (uint256 i = 0; i < amountToBack; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); artKids.push(ArtKid({ id: mintIndex, voteCount: 0, hasVoted: false, voters: new address[](0) })); } } function hasVoted(uint256 artKidTokenIndex) public view returns (bool) { require(totalSupply() >= artKidTokenIndex, "Artist does not exist."); return artKids[artKidTokenIndex].hasVoted; } function voteCount(uint artKidTokenIndex) public view returns (uint256) { require(totalSupply() >= artKidTokenIndex, "Artist does not exist."); return artKids[artKidTokenIndex].voteCount; } function vote(uint256 myNftId, uint256 artKidToVoteForIndex) public returns (bool) { // Pay winner if bidding period has ended if (block.timestamp > BIDDING_END_TIME && votingActive == true) { payWinningArtKid(); votingActive = false; return true; } // Require voting period to be active require(block.timestamp <= BIDDING_END_TIME, "Voting has ended."); // Require sale to be started require(saleStarted == true, "Sale has not started."); // Voter must own the token they're voting with require(ownerOf(myNftId) == msg.sender, "You must own the artist you are voting with."); // Voter cannot vote for a token that they own require(ownerOf(artKidToVoteForIndex) != msg.sender, "You cannot vote for an artist that you own."); // Token that's being voted with must not have voted before require(artKids[myNftId].hasVoted == false); // Token has been voted with artKids[myNftId].hasVoted = true; // Increase number of votes for token artKids[artKidToVoteForIndex].voteCount++; // Add address to voters artKids[artKidToVoteForIndex].voters.push(msg.sender); emit Vote(msg.sender, artKidToVoteForIndex, myNftId); return true; } function winningArtKid() public view returns (uint256 artKidId) { uint256 winningVoteCount = 0; for (uint256 i = 0; i < artKids.length; i++) { if (artKids[i].voteCount > winningVoteCount) { winningVoteCount = artKids[i].voteCount; artKidId = i; } } } function payWinningArtKid() internal returns (bool) { require(block.timestamp > BIDDING_END_TIME, "Voting is still active."); uint256 payoutAmount = address(this).balance / 2; uint256 winningArtKidId = winningArtKid(); finalWinner = winningArtKidId; address winnerOwner = ownerOf(winningArtKidId); payable(winnerOwner).transfer(payoutAmount); return true; } function withdraw() public onlyOwner { // Require voting period to have ended require(block.timestamp > BIDDING_END_TIME, "Voting is still active."); require(payable(msg.sender).send(address(this).balance)); } function startSale() public onlyOwner { saleStarted = true; } function pauseSale() public onlyOwner { saleStarted = false; } // If all voting has been completed before the end date, // allow owner to manually trigger payout function manuallyPayWinningArtist() public onlyOwner { // Require voting period to have ended require(block.timestamp > BIDDING_END_TIME, "Voting is still active."); votingActive = false; payWinningArtKid(); } }
Require voting period to have ended
function withdraw() public onlyOwner { require(block.timestamp > BIDDING_END_TIME, "Voting is still active."); require(payable(msg.sender).send(address(this).balance)); }
10,275,361
[ 1, 8115, 331, 17128, 3879, 358, 1240, 16926, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 598, 9446, 1435, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 2629, 18, 5508, 405, 605, 23513, 1360, 67, 4415, 67, 4684, 16, 315, 58, 17128, 353, 4859, 2695, 1199, 1769, 203, 565, 2583, 12, 10239, 429, 12, 3576, 18, 15330, 2934, 4661, 12, 2867, 12, 2211, 2934, 12296, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "../interfaces/erc20.sol"; /** * Token * * ERC-20 implementation, with mint & burn */ contract Token is IERC20 { address internal owner; address internal pendingOwner; address internal issuer; uint8 public decimals; uint256 public totalSupply; uint256 internal maxSupply; mapping (address => uint256) public override balanceOf; mapping (address => mapping (address => uint256)) public override allowance; string public name; string public symbol; event NewIssuer(address indexed issuer); event TransferOwnership(address indexed owner, bool indexed confirmed); modifier only(address role) { require(msg.sender == role); // dev: missing role _; } /** * Sets the token fields: name, symbol and decimals * * @param tokenName Name of the token * @param tokenSymbol Token Symbol * @param tokenDecimals Decimal places * @param tokenOwner Token Owner * @param tokenIssuer Token Issuer * @param tokenMaxSupply Max total supply */ constructor(string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals, address tokenOwner, address tokenIssuer, uint256 tokenMaxSupply) { require(tokenOwner != address(0)); // dev: invalid owner require(tokenIssuer != address(0)); // dev: invalid issuer require(tokenMaxSupply > 0); // dev: invalid max supply name = tokenName; symbol = tokenSymbol; decimals = tokenDecimals; owner = tokenOwner; issuer = tokenIssuer; maxSupply = tokenMaxSupply; } /** * Sets the owner * * @param newOwner Address of the new owner (must be confirmed by the new owner) */ function transferOwnership(address newOwner) external only(owner) { pendingOwner = newOwner; emit TransferOwnership(pendingOwner, false); } /** * Confirms the new owner */ function confirmOwnership() external only(pendingOwner) { owner = pendingOwner; pendingOwner = address(0); emit TransferOwnership(owner, true); } /** * Sets the issuer * * @param newIssuer Address of the issuer */ function setIssuer(address newIssuer) external only(owner) { issuer = newIssuer; emit NewIssuer(issuer); } /** * Mints {value} tokens to the {to} wallet. * * @param to The address receiving the newly minted tokens * @param value The number of tokens to mint */ function mint(address to, uint256 value) external only(issuer) { require(to != address(0)); // dev: requires non-zero address require(totalSupply + value <= maxSupply); // dev: exceeds max supply unchecked { totalSupply += value; balanceOf[to] += value; } emit Transfer(address(0), to, value); } /** * Approves the {spender} to transfer {value} tokens of the caller. * * @param spender The address which will spend the funds * @param value The value approved to be spent by the spender * @return A boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) external override returns(bool) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * Transfers {value} tokens from the caller, to {to} * * @param to The address to transfer tokens to * @param value The number of tokens to be transferred * @return A boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) external override returns (bool) { updateBalance(msg.sender, to, value); return true; } /** * Transfers {value} tokens of {from} to {to}, on behalf of the caller. * * @param from The address to transfer tokens from * @param to The address to transfer tokens to * @param value The number of tokens to be transferred * @return A boolean that indicates if the operation was successful */ function transferFrom(address from, address to, uint256 value) external override returns (bool) { require(allowance[from][msg.sender] >= value); // dev: exceeds allowance updateBalance(from, to, value); unchecked { allowance[from][msg.sender] -= value; } return true; } function updateBalance(address from, address to, uint256 value) internal { require(to != address(0)); // dev: requires non-zero address require(balanceOf[from] >= value); // dev: exceeds balance unchecked { balanceOf[from] -= value; balanceOf[to] += value; } emit Transfer(from, to, value); } }
* Mints {value} tokens to the {to} wallet. @param to The address receiving the newly minted tokens @param value The number of tokens to mint/
function mint(address to, uint256 value) external only(issuer) { unchecked { totalSupply += value; balanceOf[to] += value; } emit Transfer(address(0), to, value); }
13,118,941
[ 1, 49, 28142, 288, 1132, 97, 2430, 358, 326, 288, 869, 97, 9230, 18, 225, 358, 1021, 1758, 15847, 326, 10894, 312, 474, 329, 2430, 225, 460, 1021, 1300, 434, 2430, 358, 312, 474, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 460, 13, 203, 565, 3903, 203, 565, 1338, 12, 17567, 13, 288, 203, 203, 3639, 22893, 288, 203, 5411, 2078, 3088, 1283, 1011, 460, 31, 203, 5411, 11013, 951, 63, 869, 65, 1011, 460, 31, 203, 3639, 289, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 358, 16, 460, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x913aa64123C1835d1c63D565f83963D86EFdC41D/sources/densetsu.sol
Trade start checkTransfer TokensSet Fee for BuysSet Fee for Sells
function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 45000000000000000) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); }
2,616,871
[ 1, 22583, 787, 866, 5912, 13899, 694, 30174, 364, 605, 89, 1900, 694, 30174, 364, 348, 1165, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3238, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 203, 3639, 309, 261, 2080, 480, 3410, 1435, 597, 358, 480, 3410, 10756, 288, 203, 203, 5411, 309, 16051, 313, 14968, 3678, 13, 288, 203, 7734, 2583, 12, 2080, 422, 3410, 9334, 315, 8412, 30, 1220, 2236, 2780, 1366, 2430, 3180, 1284, 7459, 353, 3696, 8863, 203, 5411, 289, 203, 203, 5411, 2583, 12, 8949, 1648, 389, 1896, 4188, 6275, 16, 315, 8412, 30, 4238, 5947, 7214, 8863, 203, 5411, 2583, 12, 5, 4819, 87, 63, 2080, 65, 597, 401, 4819, 87, 63, 869, 6487, 315, 8412, 30, 20471, 2236, 353, 25350, 4442, 1769, 203, 203, 5411, 309, 12, 869, 480, 640, 291, 91, 438, 58, 22, 4154, 13, 288, 203, 7734, 2583, 12, 12296, 951, 12, 869, 13, 397, 3844, 411, 389, 1896, 16936, 1225, 16, 315, 8412, 30, 30918, 14399, 9230, 963, 4442, 1769, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 6835, 1345, 13937, 273, 11013, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 1426, 848, 12521, 273, 6835, 1345, 13937, 1545, 389, 22270, 5157, 861, 2 ]
pragma solidity ^0.4.23; // import 'zeppelin-solidity/contracts/ownership/DelayedClaimable.sol'; import './MultiOwnerContract.sol'; interface itoken { function freezeAccount(address _target, bool _freeze) external; function freezeAccountPartialy(address _target, uint256 _value) external; function balanceOf(address _owner) external view returns (uint256 balance); // function totalSupply() external view returns (uint256); // function transferOwnership(address newOwner) external; function allowance(address _owner, address _spender) external view returns (uint256); function initialCongress(address _congress) external; function mint(address _to, uint256 _amount) external returns (bool); function finishMinting() external returns (bool); function pause() external; function unpause() external; } // interface iParams { // function reMintCap() external view returns (uint256); // function onceMintRate() external view returns (uint256); // } contract DRCTOwner is MultiOwnerContract { string public constant AUTH_INITCONGRESS = "initCongress"; string public constant AUTH_CANMINT = "canMint"; string public constant AUTH_SETMINTAMOUNT = "setMintAmount"; string public constant AUTH_FREEZEACCOUNT = "freezeAccount"; bool congressInit = false; // bool paramsInit = false; // iParams public params; uint256 onceMintAmount; // function initParams(address _params) onlyOwner public { // require(!paramsInit); // require(_params != address(0)); // params = _params; // paramsInit = false; // } /** * @dev Function to set mint token amount * @param _value The mint value. */ function setOnceMintAmount(uint256 _value) onlyMultiOwners public { require(hasAuth(AUTH_SETMINTAMOUNT)); require(_value > 0); onceMintAmount = _value; clearAuth(AUTH_SETMINTAMOUNT); } /** * @dev change the owner of the contract from this contract address to another one. * * @param _congress the contract address that will be next Owner of the original Contract */ function initCongress(address _congress) onlyMultiOwners public { require(hasAuth(AUTH_INITCONGRESS)); require(!congressInit); itoken tk = itoken(address(ownedContract)); tk.initialCongress(_congress); clearAuth(AUTH_INITCONGRESS); congressInit = true; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @return A boolean that indicates if the operation was successful. */ function mint(address _to) onlyMultiOwners public returns (bool) { require(hasAuth(AUTH_CANMINT)); itoken tk = itoken(address(ownedContract)); bool res = tk.mint(_to, onceMintAmount); clearAuth(AUTH_CANMINT); return res; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyMultiOwners public returns (bool) { require(hasAuth(AUTH_CANMINT)); itoken tk = itoken(address(ownedContract)); bool res = tk.finishMinting(); clearAuth(AUTH_CANMINT); return res; } /** * @dev freeze the account's balance under urgent situation * * by default all the accounts will not be frozen until set freeze value as true. * * @param _target address the account should be frozen * @param _freeze bool if true, the account will be frozen */ function freezeAccountDirect(address _target, bool _freeze) onlyMultiOwners public { require(hasAuth(AUTH_FREEZEACCOUNT)); require(_target != address(0)); itoken tk = itoken(address(ownedContract)); tk.freezeAccount(_target, _freeze); clearAuth(AUTH_FREEZEACCOUNT); } /** * @dev freeze the account's balance * * by default all the accounts will not be frozen until set freeze value as true. * * @param _target address the account should be frozen * @param _freeze bool if true, the account will be frozen */ function freezeAccount(address _target, bool _freeze) onlyOwner public { require(_target != address(0)); itoken tk = itoken(address(ownedContract)); if (_freeze) { require(tk.allowance(_target, this) == tk.balanceOf(_target)); } tk.freezeAccount(_target, _freeze); } /** * @dev freeze the account's balance * * @param _target address the account should be frozen * @param _value uint256 the amount of tokens that will be frozen */ function freezeAccountPartialy(address _target, uint256 _value) onlyOwner public { require(_target != address(0)); itoken tk = itoken(address(ownedContract)); require(tk.allowance(_target, this) == _value); tk.freezeAccountPartialy(_target, _value); } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner public { itoken tk = itoken(address(ownedContract)); tk.pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner public { itoken tk = itoken(address(ownedContract)); tk.unpause(); } }
* @dev called by the owner to unpause, returns to normal state/
function unpause() onlyOwner public { itoken tk = itoken(address(ownedContract)); tk.unpause(); }
5,386,572
[ 1, 11777, 635, 326, 3410, 358, 640, 19476, 16, 1135, 358, 2212, 919, 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, 640, 19476, 1435, 1338, 5541, 1071, 288, 1377, 203, 3639, 518, 969, 13030, 273, 518, 969, 12, 2867, 12, 995, 329, 8924, 10019, 203, 3639, 13030, 18, 318, 19476, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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 @openzeppelin/contracts/token/ERC20/extensions/[email protected] /** * @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] 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] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-ERC20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File @openzeppelin/contracts/access/[email protected] /** * @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 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 contracts/code.sol contract TOKEN is ERC20, Ownable { constructor() ERC20("PayWInk", "PAYW") { _mint(msg.sender, 10000000 * 10 ** decimals()); } }
* @dev Throws if called by any account other than the owner./
modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; }
14,665,993
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 1338, 5541, 1435, 288, 203, 5411, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 5411, 389, 31, 203, 3639, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.17; /** * @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 constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address internal 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() { 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; } } /** * @titleVantageICO * @dev VantageCrowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them XVT tokens based * on a XVT token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ /** * @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)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) 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) 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; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(msg.sender, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Vantage Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale is Ownable, Pausable { using SafeMath for uint256; // The token being sold MintableToken internal token; // start and end timestamps where investments are allowed (both inclusive) uint256 private privateStartTime; uint256 private privateEndTime; uint256 private publicStartTime; uint256 private publicEndTime; // Bonuses will be calculated here of ICO and Pre-ICO (both inclusive) uint256 private privateICOBonus; // wallet address where funds will be saved address internal wallet; // base-rate of a particular Vantage token uint256 public rate; // amount of raised money in wei uint256 internal weiRaised; // internal // total supply of token uint256 private totalSupply = SafeMath.mul(200000000, 1 ether); // private supply of token uint256 private privateSupply = SafeMath.mul(40000000, 1 ether); // public supply of token uint256 private publicSupply = SafeMath.mul(70000000, 1 ether); // Team supply of token uint256 private teamAdvisorSupply = SafeMath.mul(SafeMath.div(totalSupply,100),25); // reserve supply of token uint256 private reserveSupply = SafeMath.mul(SafeMath.div(totalSupply,100),20); // Time lock or vested period of token for team allocated token uint256 public teamTimeLock; // Time lock or vested period of token for reserve allocated token uint256 public reserveTimeLock; /** * @bool checkBurnTokens * @bool grantTeamAdvisorSupply * @bool grantAdvisorSupply */ bool public checkBurnTokens; bool public grantTeamAdvisorSupply; bool public grantReserveSupply; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event TokenLeft(uint256 tokensLeft); // Vantage Crowdsale constructor function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); // Vantage token creation token = createTokenContract(); // Pre-ICO start Time privateStartTime = _startTime; // 27 march 2018 8 pm UTC // Pre-ICO end time privateEndTime = 1525219199; // 1st May 2018 11:59:pm UTC 1525219199 // // ICO start Time publicStartTime = 1530403200; // 1 july 2018 12 am UTC // ICO end Time publicEndTime = _endTime; // 20th june 2018 13:pm UTC // Base Rate of XVR Token rate = _rate; // Multi-sig wallet where funds will be saved wallet = _wallet; /** Calculations of Bonuses in ICO or Pre-ICO */ privateICOBonus = SafeMath.div(SafeMath.mul(rate,50),100); /** Vested Period calculations for team and advisors*/ teamTimeLock = SafeMath.add(publicEndTime, 3 minutes); reserveTimeLock = SafeMath.add(publicEndTime, 3 minutes); checkBurnTokens = false; grantTeamAdvisorSupply = false; grantReserveSupply = false; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // High level token purchase function function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // minimum investment should be 0.05 ETH require(weiAmount >= 50000000000000000); //50000000000000000 uint256 accessTime = now; uint256 tokens = 0; // calculating the crowdsale and Pre-crowdsale bonuses on the basis of timing require(!((accessTime > privateEndTime) && (accessTime < publicStartTime))); if ((accessTime >= privateStartTime) && (accessTime < privateEndTime)) { require(privateSupply > 0); tokens = SafeMath.add(tokens, weiAmount.mul(privateICOBonus)); tokens = SafeMath.add(tokens, weiAmount.mul(rate)); } else if ((accessTime >= publicStartTime) && (accessTime <= publicEndTime)) { tokens = SafeMath.add(tokens, weiAmount.mul(rate)); } // update state weiRaised = weiRaised.add(weiAmount); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); // funds are forwarding forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= privateStartTime && now <= publicEndTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > publicEndTime; } function burnToken() onlyOwner public returns (bool) { require(hasEnded()); require(!checkBurnTokens); totalSupply = SafeMath.sub(totalSupply, publicSupply); totalSupply = SafeMath.sub(totalSupply,privateSupply); privateSupply = 0; publicSupply = 0; checkBurnTokens = true; return true; } function grantReserveToken(address beneficiary) onlyOwner public { require((!grantReserveSupply) && (now > reserveTimeLock)); grantReserveSupply = true; token.mint(beneficiary,reserveSupply); reserveSupply = 0; } function grantTeamAdvisorToken(address beneficiary) onlyOwner public { require((!grantTeamAdvisorSupply) && (now > teamTimeLock)); grantTeamAdvisorSupply = true; token.mint(beneficiary,teamAdvisorSupply); teamAdvisorSupply = 0; } function privateSaleTransfer(address[] recipients, uint256[] values) onlyOwner public { require(!checkBurnTokens); for (uint256 i = 0; i < recipients.length; i++) { values[i] = SafeMath.mul(values[i], 1 ether); require(privateSupply >= values[i]); privateSupply = SafeMath.sub(privateSupply,values[i]); token.mint(recipients[i], values[i]); } TokenLeft(privateSupply); } function publicSaleTransfer(address[] recipients, uint256[] values) onlyOwner public { require(!checkBurnTokens); for (uint256 i = 0; i < recipients.length; i++) { values[i] = SafeMath.mul(values[i], 1 ether); require(publicSupply >= values[i]); publicSupply = SafeMath.sub(publicSupply,values[i]); token.mint(recipients[i], values[i]); } TokenLeft(publicSupply); } function getTokenAddress() onlyOwner public returns (address) { return token; } } /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 internal cap; function CappedCrowdsale(uint256 _cap) { require(_cap > 0); cap = _cap; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal constant returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } /** * @title VantageToken */ contract VantageToken is MintableToken { string public constant name = "Vantage Token"; string public constant symbol = "XVT"; uint8 public constant decimals = 18; uint256 public constant _totalSupply = SafeMath.mul(200000000, 1 ether); function VantageToken () { totalSupply = _totalSupply; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale { using SafeMath for uint256; bool isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalizeCrowdsale() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) { require(_wallet != 0x0); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale&#39;s vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 internal goal; bool private _goalReached = false; // bool public _updateTimeTransfer = false; // refund vault used to hold funds while crowdsale is running RefundVault private vault; function RefundableCrowdsale(uint256 _goal) { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We&#39;re overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public constant returns (bool) { if (weiRaised >= goal) { _goalReached = true; return true; } else if (_goalReached) { return true; } else { return false; } } function updateGoalCheck() onlyOwner public { _goalReached = true; } function getVaultAddress() onlyOwner public returns (address) { return vault; } } contract VantageCrowdsale is Crowdsale, CappedCrowdsale, RefundableCrowdsale { /** Constructor VantageICO */ function VantageCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _cap, uint256 _goal, address _wallet) CappedCrowdsale(_cap) RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet) { require(_goal <= _cap); } /**VantageToken Contract is generating from here */ function createTokenContract() internal returns (MintableToken) { return new VantageToken(); } }
@return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= privateStartTime && now <= publicEndTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; }
6,814,452
[ 1, 2463, 638, 309, 326, 2492, 848, 30143, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 923, 23164, 1435, 2713, 5381, 1135, 261, 6430, 13, 288, 203, 565, 1426, 3470, 5027, 273, 2037, 1545, 3238, 13649, 597, 2037, 1648, 1071, 25255, 31, 203, 565, 1426, 1661, 7170, 23164, 273, 1234, 18, 1132, 480, 374, 31, 203, 565, 327, 3470, 5027, 597, 1661, 7170, 23164, 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 ]
pragma solidity ^0.4.11; import './Interfaces.sol'; import './SafeMathLib.sol'; import './CoreLib.sol'; import './CoreLib2.sol'; import './CoreLib3.sol'; library BaseLib2 { using SafeMathLib for uint256; event NewDistributionPeriod(uint256 distribution_period_id); event BuyOrderCreated(uint256 _dist_period_id, uint256 _dist_day, uint256 _order_id, uint256 _order_value); //event DebugAddress(address _address); //event DebugString(string _string); //event DebugUInt(uint _value); function ProcessTransaction(Types.DataContainer storage self, RemoteWalletLib.RemoteWalletData storage data, bytes8 _ref_hash) returns(uint256) { //DebugString("ProcessTransaction"); //DebugAddress(msg.sender); require(msg.value > 0); require(msg.value >= 1 ether / 1000); //0.001 ether minimum address _ref = self.find_referral_address[_ref_hash]; require(_ref != msg.sender); if (!CoreLib2.HasVirtualWallet(self, msg.sender)) CoreLib.CreateVirtualWallet(self, msg.sender); uint256 current_dist_period_id = GetCurrentDistributionPeriod(self); //DebugString("Process"); //DebugUInt(current_dist_period_id); require(current_dist_period_id > 0 && current_dist_period_id <= self.dist_periods.length); Types.DistPeriod storage current_dist_period = self.dist_periods[current_dist_period_id-1]; require (block.timestamp.add(self._tmp_timeshift) < current_dist_period.end_time); uint256 current_daily_dist_id = FindCurrentDailyDistributionID(self, current_dist_period); Types.DailyDist storage current_daily_dist = current_dist_period.daily_dists[current_daily_dist_id-1]; current_dist_period.dist.ether_gathered = current_dist_period.dist.ether_gathered.add(msg.value); current_daily_dist.dist.ether_gathered = current_daily_dist.dist.ether_gathered.add(msg.value); uint256 new_order_id = _CreateBuyOrder(self, data, current_dist_period, current_daily_dist, _ref); return new_order_id; } function _ClaimTokensFor(Types.DataContainer storage self, address _address, uint256 _max_orders) returns(uint256) { uint256 tokens_collected = 0; //DebugString("ClaimMyTokens"); //DebugAddress(_address); uint256 order_count = self.find_orders[_address].length; //DebugUInt(order_count); if (_max_orders == 0) _max_orders = order_count; for (uint256 i = 0; i < min(_max_orders, order_count); i++) { //DebugUInt(i); uint256 order_id = self.find_orders[_address][i]; Types.Order storage order = self.orders[order_id-1]; if (!order.processed) { tokens_collected = tokens_collected.add(ProcessBuyOrder(self, order_id)); //DebugString("Back to loop"); //DebugUInt(self.find_orders[_address].length); if (order.processed) { uint256 last_order = self.find_orders[_address][order_count-1]; self.find_orders[_address][i] = last_order; self.find_orders[_address].length--; //Now we can safely lower array size } //DebugString("end iteration"); } } return tokens_collected; } function ClaimMyTokens(Types.DataContainer storage self, uint256 _max_orders) returns(uint256) { return _ClaimTokensFor(self, msg.sender, _max_orders); } function ProcessBuyOrder(Types.DataContainer storage self, uint256 _order_id) returns(uint256) { //DebugString("Entering ProcessBuyOrder"); require(_order_id > 0 && _order_id <= self.orders.length); Types.Order storage order = self.orders[_order_id-1]; return _ProcessBuyOrder(self, order); } function _ProcessBuyOrder(Types.DataContainer storage self,Types.Order storage order) returns(uint256) { //DebugString("_ProcessBuyOrder end"); Types.DistPeriod storage dist_period = self.dist_periods[order.dist_period_id-1]; Types.DailyDist storage daily_dist = dist_period.daily_dists[order.daily_dist_id-1]; uint256 current_dist_period_id = GetCurrentDistributionPeriod(self); if (order.dist_period_id == current_dist_period_id && order.daily_dist_id == GetCurrentDailyDistributionDay(self, current_dist_period_id)) { return 0; //Daily distribution is not over yet. } require(!order.processed); //DebugString("_ProcessBuyOrder passed"); uint256 daily_ref_amount = min(daily_dist.daily_amount * daily_dist.ref_order_amount / daily_dist.dist.ether_gathered, daily_dist.daily_amount * (dist_period.ref_reserve_percentage) / 100); uint256 daily_amount = daily_dist.daily_amount - daily_ref_amount; uint256 tokens_issued = (daily_amount * order.value) / daily_dist.dist.ether_gathered; uint256 ref_tokens_issued = (daily_ref_amount * order.value) / daily_dist.dist.ether_gathered; //DebugUInt(tokens_issued); require(tokens_issued == TokenStorageInterface(self.tokens_for_distribution).APIWithdrawTo(tokens_issued, order.owner)); if (!CoreLib2.HasColdStorage(self, order.owner)) CoreLib3.CreateColdStorage(self, order.owner); ColdStorageInterface cold_storage = ColdStorageInterface(CoreLib2.GetColdStorage(self, order.owner)); tokens_issued += RewardReferral(self, dist_period, daily_dist, order, ref_tokens_issued); cold_storage._APIAddRefundableTokenAmount(tokens_issued); order.processed = true; return tokens_issued; } function RewardReferral(Types.DataContainer storage self,Types.DistPeriod storage dist_period,Types.DailyDist storage daily_dist,Types.Order storage order, uint256 ref_tokens_issued) returns(uint256) { uint256 referral_amount = ref_tokens_issued * order.influence_value / (order.influence_value + order.value); uint256 referee_amount = ref_tokens_issued * order.value / (order.influence_value + order.value); if(order.ref != address(0x0)) require(referral_amount == TokenStorageInterface(self.tokens_for_distribution).APIWithdrawTo(referral_amount, order.ref)); else referee_amount += referral_amount; require(referee_amount == TokenStorageInterface(self.tokens_for_distribution).APIWithdrawTo(referee_amount, order.owner)); self.influence_value[order.ref] = order.influence_value.add(order.value * order.influence_value / (order.influence_value + order.value) ); //Increase value return referee_amount; } function _CreateBuyOrder(Types.DataContainer storage self, RemoteWalletLib.RemoteWalletData storage data, Types.DistPeriod storage dist_period,Types.DailyDist storage daily_dist, address _ref) returns(uint256) { //Search for already existing buy order uint256 existing_order_id = daily_dist.find_order_id_by_address[msg.sender]; //DebugUInt(existing_order_id); if (existing_order_id == 0) { //DebugString("Creating new order"); self.orders.length++; uint256 new_order_id = self.orders.length; Types.Order storage new_order = self.orders[new_order_id-1]; new_order.id = new_order_id; new_order.owner = msg.sender; new_order.daily_dist_id = daily_dist.id; new_order.dist_period_id = dist_period.id; if (_ref != msg.sender && _ref != address(0x0)) { new_order.ref = _ref; new_order.influence_value = self.influence_value[_ref]; daily_dist.ref_order_amount += new_order.influence_value; } daily_dist.order_ids.push(new_order.id); daily_dist.find_order_id_by_address[new_order.owner] = new_order.id; self.find_orders[msg.sender].push(new_order.id); if(self.find_referral_address[bytes8(sha256(msg.sender))] == address(0x0)) self.find_referral_address[bytes8(sha256(msg.sender))] = msg.sender; //DebugString("find_orders"); //DebugUInt(self.find_orders[msg.sender].length); //DebugAddress(msg.sender); } Types.Order storage order = self.orders[daily_dist.find_order_id_by_address[msg.sender]-1]; uint256 dev_fund_fee = msg.value * 10 / 100; uint256 new_order_value = msg.value - dev_fund_fee; order.value += msg.value; self.influence_value[msg.sender] += order.value; daily_dist.amount_in_orders += order.value; if (!CoreLib2.HasColdStorage(self, msg.sender)) CoreLib3.CreateColdStorage(self, msg.sender); ColdStorageInterface cold_storage = ColdStorageInterface(CoreLib2.GetColdStorage(self, msg.sender)); VirtualWalletInterface dev_wallet = VirtualWalletInterface(CoreLib2.GetVirtualWallet(self, data.owner)); //DebugString("Buy order created"); //DebugUInt(address(this).balance); //DebugUInt(msg.value); //DebugUInt(dev_fund_fee); //DebugUInt(new_order_value); require(cold_storage.call.value(new_order_value)()); self.locked_ether_amount = self.locked_ether_amount.add(new_order_value); require(dev_wallet.call.value(dev_fund_fee)()); //DebugUInt(address(this).balance); //DebugUInt(cold_storage.balance); //DebugUInt(dev_wallet.balance); BuyOrderCreated(dist_period.id, daily_dist.id, order.id, msg.value); return order.id; } function FindCurrentDailyDistributionID(Types.DataContainer storage self,Types.DistPeriod storage current_dist_period) returns(uint256) { uint256 seconds_since_start = block.timestamp.add(self._tmp_timeshift).sub(current_dist_period.start_time); uint256 current_dist_day = (seconds_since_start.div(RemoteWalletLib.GetSecondsInADay()))+1; //1-.. uint256 current_daily_dist_id = current_dist_period.find_daily_dist_id_by_day[current_dist_day]; return current_daily_dist_id; } //Also returns upcoming distribution function GetCurrentDistributionPeriod(Types.DataContainer storage self) constant returns(uint256) { uint256 distributions = self.dist_periods.length; uint current_distribution_id = 0; uint256 current_timestamp = block.timestamp.add(self._tmp_timeshift); Types.DistPeriod storage tmp_dist_period; uint256 i; //Only allow refunds outside of a distribution period. for (i = 0; i < distributions; i++) { tmp_dist_period = self.dist_periods[i]; bool inside_distribution = current_timestamp >= tmp_dist_period.start_time && current_timestamp < tmp_dist_period.end_time; if (inside_distribution) { current_distribution_id = tmp_dist_period.id; return current_distribution_id; } } //Not in any distribution, check for upcoming //Only works with sorted list of distributions. for (i = 0; i < distributions; i++) { tmp_dist_period = self.dist_periods[i]; if (current_timestamp <= tmp_dist_period.start_time) { current_distribution_id = tmp_dist_period.id; return current_distribution_id; } } return 0; } function GetDistributionStruct1(Types.DataContainer storage self, uint256 _dist_period_id) constant returns( uint256 ether_gathered, uint256 tokens_released, uint256 tokens_total, bool ended, uint256 start_time, uint256 end_time, uint256 days_total) { Types.DistPeriod storage dist_period = self.dist_periods[_dist_period_id-1]; return( dist_period.dist.ether_gathered, dist_period.dist.tokens_released, dist_period.dist.tokens_total, dist_period.dist.ended, dist_period.start_time, dist_period.end_time, dist_period.days_total); } function GetDistributionStruct2(Types.DataContainer storage self, uint256 _dist_period_id) constant returns( uint256 descending_amount, bytes32 caption, uint256 amount, uint256 daily_amount, uint256 ref_reserve_percentage, uint256 recent_daily_dist_id) { Types.DistPeriod storage dist_period = self.dist_periods[_dist_period_id-1]; return( dist_period.descending_amount, dist_period.caption, dist_period.amount, dist_period.daily_amount, dist_period.ref_reserve_percentage, dist_period.recent_daily_dist_id); } function GetDailyDistributionStruct1(Types.DataContainer storage self, uint256 _dist_period_id, uint256 _daily_dist_id) constant returns( uint256 day, uint256 start_time, uint256 end_time, uint256 daily_amount, uint256 ref_order_amount, uint256 amount_in_orders) { Types.DistPeriod storage current_dist_period = self.dist_periods[_dist_period_id-1]; Types.DailyDist storage current_daily_dist = current_dist_period.daily_dists[_daily_dist_id-1]; return( current_daily_dist.day, current_daily_dist.start_time, current_daily_dist.end_time, current_daily_dist.daily_amount, current_daily_dist.ref_order_amount, current_daily_dist.amount_in_orders); } function GetDailyDistributionStruct2(Types.DataContainer storage self, uint256 _dist_period_id, uint256 _daily_dist_id) constant returns( uint256 ether_gathered, uint256 tokens_released, uint256 tokens_total, bool ended) { Types.DistPeriod storage current_dist_period = self.dist_periods[_dist_period_id-1]; Types.DailyDist storage current_daily_dist = current_dist_period.daily_dists[_daily_dist_id-1]; return( current_daily_dist.dist.ether_gathered, current_daily_dist.dist.tokens_released, current_daily_dist.dist.tokens_total, current_daily_dist.dist.ended); } function GetOrderStruct(Types.DataContainer storage self, uint256 _order_id) constant returns( uint256 value, uint256 dist_period_id, uint256 daily_dist_id, uint256 received_tokens, bool processed, address owner, address ref, uint256 influence_value) { Types.Order storage order = self.orders[_order_id-1]; return( order.value, order.dist_period_id, order.daily_dist_id, order.received_tokens, order.processed, order.owner, order.ref, order.influence_value); } function GetCurrentDailyDistributionDay(Types.DataContainer storage self, uint256 _dist_period_id) constant returns(uint256) { require(_dist_period_id > 0 && _dist_period_id <= self.dist_periods.length); Types.DistPeriod storage current_dist_period = self.dist_periods[_dist_period_id-1]; return FindCurrentDailyDistributionID(self, current_dist_period); } function Distribute(Types.DataContainer storage self, bool _absolute, uint256 _start_time, uint256 _days, uint256 _amount, uint256 _descending_amount, bytes32 _caption) returns(uint256) { if (_start_time == 0) _start_time = block.timestamp.add(self._tmp_timeshift); else { if (!_absolute) _start_time = block.timestamp.add(self._tmp_timeshift).add(_start_time); //Shift } require(_start_time >= block.timestamp.add(self._tmp_timeshift)); require(_days > 0); require(_amount > 0); //Make sure it can be evenly distributed require(_amount.sub((_amount.div(_days)).mul(_days)) == 0); uint256 end_time = _start_time + _days.mul(RemoteWalletLib.GetSecondsInADay()); //make sure no collisions occur for (uint256 i = 0; i < self.dist_periods.length; i++) { Types.DistPeriod storage tmp_dist_period = self.dist_periods[i]; bool collides = end_time > tmp_dist_period.start_time && _start_time < tmp_dist_period.end_time; require(!collides); } self.distributed += _amount; //Create a new dist period. return CreateDistributionPeriod(self, _start_time, _days, _amount, _descending_amount, _caption); } function CreateDistributionPeriod(Types.DataContainer storage self, uint256 _start_time, uint256 _days, uint256 _amount, uint256 _descending_amount, bytes32 _caption) returns(uint256) { self.dist_periods.length++; uint256 new_dist_period_id = self.dist_periods.length; Types.DistPeriod storage new_dist_period = self.dist_periods[new_dist_period_id-1]; new_dist_period.id = new_dist_period_id; new_dist_period.start_time = _start_time; new_dist_period.end_time = _start_time.add(_days.mul(RemoteWalletLib.GetSecondsInADay())); new_dist_period.days_total = _days; new_dist_period.amount = _amount; new_dist_period.daily_amount = _amount.div(_days); new_dist_period.ref_reserve_percentage = 5; //max of 5% will be split between referals new_dist_period.caption = _caption; new_dist_period.descending_amount = _descending_amount; uint256 bonus_amount = _descending_amount.div(_days); uint256 series_sum = (_days * (_days - 1 )).div(2) * bonus_amount; for (uint256 i = 1; i <= _days; i++) { CreateDailyDistribution(self, new_dist_period, i, (new_dist_period.amount - series_sum).div(_days) + bonus_amount * (_days - i)); } new_dist_period.dist.tokens_total = _amount; NewDistributionPeriod(new_dist_period_id); return new_dist_period_id; } function CreateDailyDistribution(Types.DataContainer storage self, Types.DistPeriod storage current_dist_period, uint256 _day, uint256 _amount) returns(uint256) { current_dist_period.daily_dists.length++; uint256 current_daily_dist_id = current_dist_period.daily_dists.length; current_dist_period.find_daily_dist_id_by_day[_day] = current_daily_dist_id; Types.DailyDist storage current_daily_dist = current_dist_period.daily_dists[current_daily_dist_id-1]; current_daily_dist.id = current_daily_dist_id; current_daily_dist.day = _day; current_daily_dist.daily_amount = _amount; current_daily_dist.start_time = current_dist_period.start_time.add((_day-1).mul(RemoteWalletLib.GetSecondsInADay())); current_daily_dist.end_time = current_dist_period.start_time.add(_day.mul(RemoteWalletLib.GetSecondsInADay())); return current_daily_dist_id; } function _InitSpecialPermissions(Types.DataContainer storage self, RemoteWalletLib.RemoteWalletData storage data) { //SuperMajority group controls over foundation tokens TokenStorageInterface foundation_tokens = TokenStorageInterface(self.tokens_for_distribution); foundation_tokens.APISetPermissionBySig(bytes4(sha3("APISuperMajorityCall(address,bytes4)")), self.supermajority_group, true, false); //SuperMajority group controls over foundation wallet VirtualWalletInterface foundation_wallet = VirtualWalletInterface(self.foundation_virtual_wallet); foundation_wallet.APISetPermissionBySig(bytes4(sha3("APISuperMajorityCall(address,bytes4)")), self.supermajority_group, true, false); //Which functions supermajority is allowed to call RemoteWalletLib._SetPermissionBySig(data, bytes4(sha3("SetBurnRequired(bool)")), self.supermajority_group, true, true); //Can disable token burn during refund, however it can have negative impact on economy. It's a double-edged sword. RemoteWalletLib._SetPermissionBySig(data, bytes4(sha3("SetSuperMajorityAddress(address)")), self.supermajority_group, true, true); //Can upgrade itself, however won't change permissions required. } function SetSuperMajorityAddress(Types.DataContainer storage self, RemoteWalletLib.RemoteWalletData storage data, address _supermajority) { self.supermajority_group = _supermajority; _InitSpecialPermissions(self, data); } function max(uint256 a, uint256 b) constant returns (uint256) { return (a>b)?a:b; } function min(uint256 a, uint256 b) constant returns (uint256) { return !(a>b)?a:b; } }
max of 5% will be split between referals
new_dist_period.ref_reserve_percentage = 5;
937,057
[ 1, 1896, 434, 1381, 9, 903, 506, 1416, 3086, 8884, 1031, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 394, 67, 4413, 67, 6908, 18, 1734, 67, 455, 6527, 67, 18687, 273, 1381, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IMasterChef.sol"; import "./interfaces/IVault.sol"; import "./interfaces/ILockManager.sol"; import "./interfaces/IERC20Extended.sol"; import "./lib/SafeERC20.sol"; import "./lib/ReentrancyGuard.sol"; /** * @title RewardsManager * @dev Controls rewards distribution for network */ contract RewardsManager is ReentrancyGuard { using SafeERC20 for IERC20Extended; /// @notice Current owner of this contract address public owner; /// @notice Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardTokenDebt; // Reward debt for reward token. See explanation below. uint256 sushiRewardDebt; // Reward debt for Sushi rewards. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardsPerShare` (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. } /// @notice Info of each pool. struct PoolInfo { IERC20Extended token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per block. uint256 lastRewardBlock; // Last block number where reward tokens were distributed. uint256 accRewardsPerShare; // Accumulated reward tokens per share, times 1e12. See below. uint32 vestingPercent; // Percentage of rewards that vest (measured in bips: 500,000 bips = 50% of rewards) uint16 vestingPeriod; // Vesting period in days for vesting rewards uint16 vestingCliff; // Vesting cliff in days for vesting rewards uint256 totalStaked; // Total amount of token staked via Rewards Manager bool vpForDeposit; // Do users get voting power for deposits of this token? bool vpForVesting; // Do users get voting power for vesting balances? } /// @notice Reward token IERC20Extended public rewardToken; /// @notice SUSHI token IERC20Extended public sushiToken; /// @notice Sushi Master Chef IMasterChef public masterChef; /// @notice Vault for vesting tokens IVault public vault; /// @notice LockManager contract ILockManager public lockManager; /// @notice Reward tokens rewarded per block. uint256 public rewardTokensPerBlock; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Mapping of Sushi tokens to MasterChef pids mapping (address => uint256) public sushiPools; /// @notice Info of each user that stakes tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @notice Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; /// @notice The block number when rewards start. uint256 public startBlock; /// @notice only owner can call function modifier onlyOwner { require(msg.sender == owner, "not owner"); _; } /// @notice Event emitted when a user deposits funds in the rewards manager event Deposit(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds + rewards from the rewards manager event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds from the rewards manager without claiming rewards event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when new pool is added to the rewards manager event PoolAdded(uint256 indexed pid, address indexed token, uint256 allocPoints, uint256 totalAllocPoints, uint256 rewardStartBlock, uint256 sushiPid, bool vpForDeposit, bool vpForVesting); /// @notice Event emitted when pool allocation points are updated event PoolUpdated(uint256 indexed pid, uint256 oldAllocPoints, uint256 newAllocPoints, uint256 newTotalAllocPoints); /// @notice Event emitted when the owner of the rewards manager contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /// @notice Event emitted when the amount of reward tokens per block is updated event ChangedRewardTokensPerBlock(uint256 indexed oldRewardTokensPerBlock, uint256 indexed newRewardTokensPerBlock); /// @notice Event emitted when the rewards start block is set event SetRewardsStartBlock(uint256 indexed startBlock); /// @notice Event emitted when contract address is changed event ChangedAddress(string indexed addressType, address indexed oldAddress, address indexed newAddress); /** * @notice Create a new Rewards Manager contract * @param _owner owner of contract * @param _lockManager address of LockManager contract * @param _vault address of Vault contract * @param _rewardToken address of token that is being offered as a reward * @param _sushiToken address of SUSHI token * @param _masterChef address of SushiSwap MasterChef contract * @param _startBlock block number when rewards will start * @param _rewardTokensPerBlock initial amount of reward tokens to be distributed per block */ constructor( address _owner, address _lockManager, address _vault, address _rewardToken, address _sushiToken, address _masterChef, uint256 _startBlock, uint256 _rewardTokensPerBlock ) { owner = _owner; emit ChangedOwner(address(0), _owner); lockManager = ILockManager(_lockManager); emit ChangedAddress("LOCK_MANAGER", address(0), _lockManager); vault = IVault(_vault); emit ChangedAddress("VAULT", address(0), _vault); rewardToken = IERC20Extended(_rewardToken); emit ChangedAddress("REWARD_TOKEN", address(0), _rewardToken); sushiToken = IERC20Extended(_sushiToken); emit ChangedAddress("SUSHI_TOKEN", address(0), _sushiToken); masterChef = IMasterChef(_masterChef); emit ChangedAddress("MASTER_CHEF", address(0), _masterChef); startBlock = _startBlock == 0 ? block.number : _startBlock; emit SetRewardsStartBlock(startBlock); rewardTokensPerBlock = _rewardTokensPerBlock; emit ChangedRewardTokensPerBlock(0, _rewardTokensPerBlock); rewardToken.safeIncreaseAllowance(address(vault), type(uint256).max); } /** * @notice View function to see current poolInfo array length * @return pool length */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Add a new reward token to the pool * @dev Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. * @param allocPoint Number of allocation points to allot to this token/pool * @param token The token that will be staked for rewards * @param vestingPercent The percentage of rewards from this pool that will vest * @param vestingPeriod The number of days for the vesting period * @param vestingCliff The number of days for the vesting cliff * @param withUpdate if specified, update all pools before adding new pool * @param sushiPid The pid of the Sushiswap pool in the Masterchef contract (if exists, otherwise provide zero) * @param vpForDeposit If true, users get voting power for deposits * @param vpForVesting If true, users get voting power for vesting balances */ function add( uint256 allocPoint, address token, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool withUpdate, uint256 sushiPid, bool vpForDeposit, bool vpForVesting ) external onlyOwner { if (withUpdate) { massUpdatePools(); } uint256 rewardStartBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + allocPoint; poolInfo.push(PoolInfo({ token: IERC20Extended(token), allocPoint: allocPoint, lastRewardBlock: rewardStartBlock, accRewardsPerShare: 0, vestingPercent: vestingPercent, vestingPeriod: vestingPeriod, vestingCliff: vestingCliff, totalStaked: 0, vpForDeposit: vpForDeposit, vpForVesting: vpForVesting })); if (sushiPid != uint256(0)) { sushiPools[token] = sushiPid; IERC20Extended(token).safeIncreaseAllowance(address(masterChef), type(uint256).max); } IERC20Extended(token).safeIncreaseAllowance(address(vault), type(uint256).max); emit PoolAdded(poolInfo.length - 1, token, allocPoint, totalAllocPoint, rewardStartBlock, sushiPid, vpForDeposit, vpForVesting); } /** * @notice Update the given pool's allocation points * @dev Can only be called by the owner * @param pid The RewardManager pool id * @param allocPoint New number of allocation points for pool * @param withUpdate if specified, update all pools before setting allocation points */ function set( uint256 pid, uint256 allocPoint, bool withUpdate ) external onlyOwner { if (withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[pid].allocPoint + allocPoint; emit PoolUpdated(pid, poolInfo[pid].allocPoint, allocPoint, totalAllocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Returns true if rewards are actively being accumulated */ function rewardsActive() public view returns (bool) { return block.number >= startBlock && totalAllocPoint > 0 ? true : false; } /** * @notice Return reward multiplier over the given from to to block. * @param from From block number * @param to To block number * @return multiplier */ function getMultiplier(uint256 from, uint256 to) public pure returns (uint256) { return to > from ? to - from : 0; } /** * @notice View function to see pending reward tokens on frontend. * @param pid pool id * @param account user account to check * @return pending rewards */ function pendingRewardTokens(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 accRewardsPerShare = pool.accRewardsPerShare; uint256 tokenSupply = pool.totalStaked; if (block.number > pool.lastRewardBlock && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; accRewardsPerShare = accRewardsPerShare + totalReward * 1e12 / tokenSupply; } uint256 accumulatedRewards = user.amount * accRewardsPerShare / 1e12; if (accumulatedRewards < user.rewardTokenDebt) { return 0; } return accumulatedRewards - user.rewardTokenDebt; } /** * @notice View function to see pending SUSHI on frontend. * @param pid pool id * @param account user account to check * @return pending SUSHI rewards */ function pendingSushi(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid == uint256(0)) { return 0; } IMasterChef.PoolInfo memory sushiPool = masterChef.poolInfo(sushiPid); uint256 sushiPerBlock = masterChef.sushiPerBlock(); uint256 totalSushiAllocPoint = masterChef.totalAllocPoint(); uint256 accSushiPerShare = sushiPool.accSushiPerShare; uint256 lpSupply = sushiPool.lpToken.balanceOf(address(masterChef)); if (block.number > sushiPool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = masterChef.getMultiplier(sushiPool.lastRewardBlock, block.number); uint256 sushiReward = multiplier * sushiPerBlock * sushiPool.allocPoint / totalSushiAllocPoint; accSushiPerShare = accSushiPerShare + sushiReward * 1e12 / lpSupply; } uint256 accumulatedSushi = user.amount * accSushiPerShare / 1e12; if (accumulatedSushi < user.sushiRewardDebt) { return 0; } return accumulatedSushi - user.sushiRewardDebt; } /** * @notice Update reward variables for all pools * @dev Be careful of gas spending! */ function massUpdatePools() public { for (uint256 pid = 0; pid < poolInfo.length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date * @param pid pool id */ function updatePool(uint256 pid) public { PoolInfo storage pool = poolInfo[pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 tokenSupply = pool.totalStaked; if (tokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; pool.accRewardsPerShare = pool.accRewardsPerShare + totalReward * 1e12 / tokenSupply; pool.lastRewardBlock = block.number; } /** * @notice Deposit tokens to RewardsManager for rewards allocation. * @param pid pool id * @param amount number of tokens to deposit */ function deposit(uint256 pid, uint256 amount) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _deposit(pid, amount, pool, user); } /** * @notice Deposit tokens to RewardsManager for rewards allocation, using permit for approval * @dev It is up to the frontend developer to ensure the pool token implements permit - otherwise this will fail * @param pid pool id * @param amount number of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit( uint256 pid, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.token.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(pid, amount, pool, user); } /** * @notice Withdraw tokens from RewardsManager, claiming rewards. * @param pid pool id * @param amount number of tokens to withdraw */ function withdraw(uint256 pid, uint256 amount) external nonReentrant { require(amount > 0, "RM::withdraw: amount must be > 0"); PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _withdraw(pid, amount, pool, user); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool id */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.withdraw(sushiPid, user.amount); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), user.amount); } pool.totalStaked = pool.totalStaked - user.amount; pool.token.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewardTokenDebt = 0; user.sushiRewardDebt = 0; } } /** * @notice Set approvals for external addresses to use contract tokens * @dev Can only be called by the owner * @param tokensToApprove the tokens to approve * @param approvalAmounts the token approval amounts * @param spender the address to allow spending of token */ function tokenAllow( address[] memory tokensToApprove, uint256[] memory approvalAmounts, address spender ) external onlyOwner { require(tokensToApprove.length == approvalAmounts.length, "RM::tokenAllow: not same length"); for(uint i = 0; i < tokensToApprove.length; i++) { IERC20Extended token = IERC20Extended(tokensToApprove[i]); if (token.allowance(address(this), spender) != type(uint256).max) { token.safeApprove(spender, approvalAmounts[i]); } } } /** * @notice Rescue (withdraw) tokens from the smart contract * @dev Can only be called by the owner * @param tokens the tokens to withdraw * @param amounts the amount of each token to withdraw. If zero, withdraws the maximum allowed amount for each token * @param receiver the address that will receive the tokens */ function rescueTokens( address[] calldata tokens, uint256[] calldata amounts, address receiver ) external onlyOwner { require(tokens.length == amounts.length, "RM::rescueTokens: not same length"); for (uint i = 0; i < tokens.length; i++) { IERC20Extended token = IERC20Extended(tokens[i]); uint256 withdrawalAmount; uint256 tokenBalance = token.balanceOf(address(this)); uint256 tokenAllowance = token.allowance(address(this), receiver); if (amounts[i] == 0) { if (tokenBalance > tokenAllowance) { withdrawalAmount = tokenAllowance; } else { withdrawalAmount = tokenBalance; } } else { require(tokenBalance >= amounts[i], "RM::rescueTokens: contract balance too low"); require(tokenAllowance >= amounts[i], "RM::rescueTokens: increase token allowance"); withdrawalAmount = amounts[i]; } token.safeTransferFrom(address(this), receiver, withdrawalAmount); } } /** * @notice Set new rewards per block * @dev Can only be called by the owner * @param newRewardTokensPerBlock new amount of reward token to reward each block */ function setRewardsPerBlock(uint256 newRewardTokensPerBlock) external onlyOwner { emit ChangedRewardTokensPerBlock(rewardTokensPerBlock, newRewardTokensPerBlock); rewardTokensPerBlock = newRewardTokensPerBlock; } /** * @notice Set new SUSHI token address * @dev Can only be called by the owner * @param newToken address of new SUSHI token */ function setSushiToken(address newToken) external onlyOwner { emit ChangedAddress("SUSHI_TOKEN", address(sushiToken), newToken); sushiToken = IERC20Extended(newToken); } /** * @notice Set new MasterChef address * @dev Can only be called by the owner * @param newAddress address of new MasterChef */ function setMasterChef(address newAddress) external onlyOwner { emit ChangedAddress("MASTER_CHEF", address(masterChef), newAddress); masterChef = IMasterChef(newAddress); } /** * @notice Set new Vault address * @param newAddress address of new Vault */ function setVault(address newAddress) external onlyOwner { emit ChangedAddress("VAULT", address(vault), newAddress); vault = IVault(newAddress); } /** * @notice Set new LockManager address * @param newAddress address of new LockManager */ function setLockManager(address newAddress) external onlyOwner { emit ChangedAddress("LOCK_MANAGER", address(lockManager), newAddress); lockManager = ILockManager(newAddress); } /** * @notice Change owner of Rewards Manager contract * @dev Can only be called by the owner * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "RM::changeOwner: not valid address"); emit ChangedOwner(owner, newOwner); owner = newOwner; } /** * @notice Internal implementation of deposit * @param pid pool id * @param amount number of tokens to deposit * @param pool the pool info * @param user the user info */ function _deposit( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; uint256 pendingSushiTokens = 0; if (user.amount > 0) { uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; } } pool.token.safeTransferFrom(msg.sender, address(this), amount); pool.totalStaked = pool.totalStaked + amount; user.amount = user.amount + amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); user.sushiRewardDebt = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; masterChef.deposit(sushiPid, amount); } if (amount > 0 && pool.vpForDeposit) { lockManager.grantVotingPower(msg.sender, address(pool.token), amount); } if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } emit Deposit(msg.sender, pid, amount); } /** * @notice Internal implementation of withdraw * @param pid pool id * @param amount number of tokens to withdraw * @param pool the pool info * @param user the user info */ function _withdraw( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { require(user.amount >= amount, "RM::_withdraw: amount > user balance"); updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); uint256 pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; masterChef.withdraw(sushiPid, amount); user.sushiRewardDebt = (user.amount - amount) * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } } uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; user.amount = user.amount - amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), amount); } pool.totalStaked = pool.totalStaked - amount; pool.token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } /** * @notice Internal function used to distribute rewards, optionally vesting a % * @param account account that is due rewards * @param rewardAmount amount of rewards to distribute * @param vestingPercent percent of rewards to vest in bips * @param vestingPeriod number of days over which to vest rewards * @param vestingCliff number of days for vesting cliff * @param vestingVotingPower if true, grant voting power for vesting balance */ function _distributeRewards( address account, uint256 rewardAmount, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool vestingVotingPower ) internal { uint256 vestingRewards = rewardAmount * vestingPercent / 1000000; rewardToken.mint(address(this), rewardAmount); vault.lockTokens(address(rewardToken), address(this), account, 0, vestingRewards, vestingPeriod, vestingCliff, vestingVotingPower); rewardToken.safeTransfer(msg.sender, rewardAmount - vestingRewards); } /** * @notice Safe SUSHI transfer function, just in case if rounding error causes pool to not have enough SUSHI. * @param to account that is receiving SUSHI * @param amount amount of SUSHI to send */ function _safeSushiTransfer(address to, uint256 amount) internal { uint256 sushiBalance = sushiToken.balanceOf(address(this)); if (amount > sushiBalance) { sushiToken.safeTransfer(to, sushiBalance); } else { sushiToken.safeTransfer(to, amount); } } } // 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"; interface IERC20Burnable is IERC20 { function burn(uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Metadata.sol"; import "./IERC20Mintable.sol"; import "./IERC20Burnable.sol"; import "./IERC20Permit.sol"; import "./IERC20TransferWithAuth.sol"; import "./IERC20SafeAllowance.sol"; interface IERC20Extended is IERC20Metadata, IERC20Mintable, IERC20Burnable, IERC20Permit, IERC20TransferWithAuth, IERC20SafeAllowance {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20Mintable is IERC20 { function mint(address dst, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20Permit is IERC20 { function getDomainSeparator() external view returns (bytes32); function DOMAIN_TYPEHASH() external view returns (bytes32); function VERSION_HASH() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function nonces(address) external view returns (uint); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20SafeAllowance is IERC20 { function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20TransferWithAuth is IERC20 { function transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ILockManager { struct LockedStake { uint256 amount; uint256 votingPower; } function getAmountStaked(address staker, address stakedToken) external view returns (uint256); function getStake(address staker, address stakedToken) external view returns (LockedStake memory); function calculateVotingPower(address token, uint256 amount) external view returns (uint256); function grantVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerGranted); function removeVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerRemoved); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IMasterChef { struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. } function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function updatePool(uint256 _pid) external; function sushiPerBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IVault { struct Lock { address token; address receiver; uint48 startTime; uint16 vestingDurationInDays; uint16 cliffDurationInDays; uint256 amount; uint256 amountClaimed; uint256 votingPower; } struct LockBalance { uint256 id; uint256 claimableAmount; Lock lock; } struct TokenBalance { uint256 totalAmount; uint256 claimableAmount; uint256 claimedAmount; uint256 votingPower; } function lockTokens(address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 lockDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower) external; function lockTokensWithPermit(address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 lockDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function claimUnlockedTokenAmounts(uint256[] memory lockIds, uint256[] memory amounts) external; function claimAllUnlockedTokens(uint256[] memory lockIds) external; function tokenLocks(uint256 lockId) external view returns(Lock memory); function allActiveLockIds() external view returns(uint256[] memory); function allActiveLocks() external view returns(Lock[] memory); function allActiveLockBalances() external view returns(LockBalance[] memory); function activeLockIds(address receiver) external view returns(uint256[] memory); function allLocks(address receiver) external view returns(Lock[] memory); function activeLocks(address receiver) external view returns(Lock[] memory); function activeLockBalances(address receiver) external view returns(LockBalance[] memory); function totalTokenBalance(address token) external view returns(TokenBalance memory balance); function tokenBalance(address token, address receiver) external view returns(TokenBalance memory balance); function lockBalance(uint256 lockId) external view returns (LockBalance memory); function claimableBalance(uint256 lockId) external view returns (uint256); function extendLock(uint256 lockId, uint16 vestingDaysToAdd, uint16 cliffDaysToAdd) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } 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 Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
* @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 pragma solidity ^0.8.0; ) 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 { 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)); } } 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)); } } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
212,401
[ 1, 9890, 654, 39, 3462, 225, 4266, 10422, 6740, 4232, 39, 3462, 5295, 716, 604, 603, 5166, 261, 13723, 326, 1147, 6835, 1135, 629, 2934, 13899, 716, 327, 1158, 460, 261, 464, 3560, 15226, 578, 604, 603, 5166, 13, 854, 2546, 3260, 16, 1661, 17, 266, 1097, 310, 4097, 854, 12034, 358, 506, 6873, 18, 2974, 999, 333, 5313, 1846, 848, 527, 279, 1375, 9940, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 68, 3021, 358, 3433, 6835, 16, 1492, 5360, 1846, 358, 745, 326, 4183, 5295, 487, 1375, 2316, 18, 4626, 5912, 5825, 13, 9191, 5527, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 654, 39, 3462, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 445, 4183, 5912, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 262, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 18, 9663, 16, 358, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 1265, 18, 9663, 16, 628, 16, 358, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 12053, 537, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 288, 203, 3639, 2583, 12, 203, 5411, 261, 1132, 422, 374, 13, 747, 261, 2316, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 17571, 264, 13, 422, 374, 3631, 203, 5411, 315, 9890, 654, 39, 3462, 30, 6617, 537, 628, 1661, 17, 7124, 358, 1661, 17, 7124, 1699, 1359, 6, 203, 3639, 11272, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 12908, 537, 18, 2 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; //Interface import { ITokenERC20 } from "../interfaces/token/ITokenERC20.sol"; // Token import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol"; // Security import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; // Signature utils import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol"; // Meta transactions import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; // Utils import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; // Thirdweb top-level import "../interfaces/ITWFee.sol"; contract TokenERC20 is Initializable, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable, ERC20VotesUpgradeable, ITokenERC20, AccessControlEnumerableUpgradeable { using ECDSAUpgradeable for bytes32; bytes32 private constant MODULE_TYPE = bytes32("TokenERC20"); uint256 private constant VERSION = 1; bytes32 private constant TYPEHASH = keccak256( "MintRequest(address to,address primarySaleRecipient,uint256 quantity,uint256 price,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)" ); bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 internal constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 internal constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); /// @dev The thirdweb contract with fee related information. ITWFee internal immutable thirdwebFee; /// @dev Returns the URI for the storefront-level metadata of the contract. string public contractURI; /// @dev Max bps in the thirdweb system uint128 internal constant MAX_BPS = 10_000; /// @dev The % of primary sales collected by the contract as fees. uint128 internal platformFeeBps; /// @dev The adress that receives all primary sales value. address internal platformFeeRecipient; /// @dev The adress that receives all primary sales value. address public primarySaleRecipient; /// @dev Mapping from mint request UID => whether the mint request is processed. mapping(bytes32 => bool) private minted; constructor(address _thirdwebFee) initializer { thirdwebFee = ITWFee(_thirdwebFee); } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _name, string memory _symbol, string memory _contractURI, address[] memory _trustedForwarders, address _primarySaleRecipient, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { __ERC2771Context_init_unchained(_trustedForwarders); __ERC20Permit_init(_name); __ERC20_init_unchained(_name, _symbol); contractURI = _contractURI; primarySaleRecipient = _primarySaleRecipient; platformFeeRecipient = _platformFeeRecipient; platformFeeBps = uint128(_platformFeeBps); _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); _setupRole(TRANSFER_ROLE, _defaultAdmin); _setupRole(MINTER_ROLE, _defaultAdmin); _setupRole(PAUSER_ROLE, _defaultAdmin); _setupRole(TRANSFER_ROLE, address(0)); } /// @dev Returns the module type of the contract. function contractType() external pure virtual returns (bytes32) { return MODULE_TYPE; } /// @dev Returns the version of the contract. function contractVersion() external pure virtual returns (uint8) { return uint8(VERSION); } function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) { super._afterTokenTransfer(from, to, amount); } /// @dev Runs on every transfer. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "transfers restricted."); } } function _mint(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) { super._mint(account, amount); } function _burn(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) { super._burn(account, amount); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mintTo(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "not minter."); _mintTo(to, amount); } /// @dev Verifies that a mint request is signed by an account holding MINTER_ROLE (at the time of the function call). function verify(MintRequest calldata _req, bytes calldata _signature) public view returns (bool, address) { address signer = recoverAddress(_req, _signature); return (!minted[_req.uid] && hasRole(MINTER_ROLE, signer), signer); } /// @dev Mints tokens according to the provided mint request. function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant { address signer = verifyRequest(_req, _signature); address receiver = _req.to == address(0) ? _msgSender() : _req.to; address saleRecipient = _req.primarySaleRecipient == address(0) ? primarySaleRecipient : _req.primarySaleRecipient; collectPrice(saleRecipient, _req.currency, _req.price); _mintTo(receiver, _req.quantity); emit TokensMintedWithSignature(signer, receiver, _req); } /// @dev Lets a module admin set the default recipient of all primary sales. function setPrimarySaleRecipient(address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) { primarySaleRecipient = _saleRecipient; emit PrimarySaleRecipientUpdated(_saleRecipient); } /// @dev Lets a module admin update the fees on primary sales. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_platformFeeBps <= MAX_BPS, "bps <= 10000."); platformFeeBps = uint64(_platformFeeBps); platformFeeRecipient = _platformFeeRecipient; emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps); } /// @dev Returns the platform fee bps and recipient. function getPlatformFeeInfo() external view returns (address, uint16) { return (platformFeeRecipient, uint16(platformFeeBps)); } /// @dev Collects and distributes the primary sale value of tokens being claimed. function collectPrice( address _primarySaleRecipient, address _currency, uint256 _price ) internal { if (_price == 0) { return; } uint256 platformFees = (_price * platformFeeBps) / MAX_BPS; (address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.PRIMARY_SALE); uint256 twFee = (_price * twFeeBps) / MAX_BPS; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == _price, "must send total price."); } CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees); CurrencyTransferLib.transferCurrency(_currency, _msgSender(), twFeeRecipient, twFee); CurrencyTransferLib.transferCurrency( _currency, _msgSender(), _primarySaleRecipient, _price - platformFees - twFee ); } /// @dev Mints `amount` of tokens to `to` function _mintTo(address _to, uint256 _amount) internal { _mint(_to, _amount); emit TokensMinted(_to, _amount); } /// @dev Verifies that a mint request is valid. function verifyRequest(MintRequest calldata _req, bytes calldata _signature) internal returns (address) { (bool success, address signer) = verify(_req, _signature); require(success, "invalid signature"); require( _req.validityStartTimestamp <= block.timestamp && _req.validityEndTimestamp >= block.timestamp, "request expired" ); minted[_req.uid] = true; return signer; } /// @dev Returns the address of the signer of the mint request. function recoverAddress(MintRequest calldata _req, bytes calldata _signature) internal view returns (address) { return _hashTypedDataV4(keccak256(_encodeRequest(_req))).recover(_signature); } /// @dev Resolves 'stack too deep' error in `recoverAddress`. function _encodeRequest(MintRequest calldata _req) internal pure returns (bytes memory) { return abi.encode( TYPEHASH, _req.to, _req.primarySaleRecipient, _req.quantity, _req.price, _req.currency, _req.validityStartTimestamp, _req.validityEndTimestamp, _req.uid ); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser."); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser."); _unpause(); } /// @dev Sets contract URI for the storefront-level metadata of the contract. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { contractURI = _uri; } function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { return ERC2771ContextUpgradeable._msgSender(); } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { return ERC2771ContextUpgradeable._msgData(); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../IThirdwebContract.sol"; import "../IThirdwebPlatformFee.sol"; import "../IThirdwebPrimarySale.sol"; interface ITokenERC20 is IThirdwebContract, IThirdwebPrimarySale, IThirdwebPlatformFee, IERC20Upgradeable { /** * @notice The body of a request to mint tokens. * * @param to The receiver of the tokens to mint. * @param primarySaleRecipient The receiver of the primary sale funds from the mint. * @param quantity The quantity of tpkens to mint. * @param price Price to pay for minting with the signature. * @param currency The currency in which the price per token must be paid. * @param validityStartTimestamp The unix timestamp after which the request is valid. * @param validityEndTimestamp The unix timestamp after which the request expires. * @param uid A unique identifier for the request. */ struct MintRequest { address to; address primarySaleRecipient; uint256 quantity; uint256 price; address currency; uint128 validityStartTimestamp; uint128 validityEndTimestamp; bytes32 uid; } /// @dev Emitted when an account with MINTER_ROLE mints an NFT. event TokensMinted(address indexed mintedTo, uint256 quantityMinted); /// @dev Emitted when tokens are minted. event TokensMintedWithSignature(address indexed signer, address indexed mintedTo, MintRequest mintRequest); /// @dev Emitted when a new sale recipient is set. event PrimarySaleRecipientUpdated(address indexed recipient); /// @dev Emitted when fee on primary sales is updated. event PlatformFeeInfoUpdated(address platformFeeRecipient, uint256 platformFeeBps); /** * @notice Verifies that a mint request is signed by an account holding * MINTER_ROLE (at the time of the function call). * * @param req The mint request. * @param signature The signature produced by an account signing the mint request. * * returns (success, signer) Result of verification and the recovered address. */ function verify(MintRequest calldata req, bytes calldata signature) external view returns (bool success, address signer); /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mintTo(address to, uint256 amount) external; /** * @notice Mints an NFT according to the provided mint request. * * @param req The mint request. * @param signature he signature produced by an account signing the mint request. */ function mintWithSignature(MintRequest calldata req, bytes calldata signature) external payable; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal onlyInitializing { } function __ERC20Burnable_init_unchained() internal onlyInitializing { } /** * @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 { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } /** * @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 v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol) pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal onlyInitializing { } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } /** * @dev 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) (token/ERC20/extensions/ERC20Votes.sol) pragma solidity ^0.8.0; import "./draft-ERC20PermitUpgradeable.sol"; import "../../../utils/math/MathUpgradeable.sol"; import "../../../governance/utils/IVotesUpgradeable.sol"; import "../../../utils/math/SafeCastUpgradeable.sol"; import "../../../utils/cryptography/ECDSAUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * * _Available since v4.2._ */ abstract contract ERC20VotesUpgradeable is Initializable, IVotesUpgradeable, ERC20PermitUpgradeable { function __ERC20Votes_init() internal onlyInitializing { } function __ERC20Votes_init_unchained() internal onlyInitializing { } struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCastUpgradeable.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual override returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view virtual override returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual override { _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSAUpgradeable.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(block.number), votes: SafeCastUpgradeable.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } /** * @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[47] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) 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 onlyInitializing { } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } 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 virtual 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 virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } /** * @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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSAUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal onlyInitializing { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } /** * @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 v4.4.0 (metatx/ERC2771Context.sol) pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @dev Context variant with ERC2771 support. */ abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable { mapping(address => bool) private _trustedForwarder; function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing { __Context_init_unchained(); __ERC2771Context_init_unchained(trustedForwarder); } function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing { for (uint256 i = 0; i < trustedForwarder.length; i++) { _trustedForwarder[trustedForwarder[i]] = true; } } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return _trustedForwarder[forwarder]; } function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return super._msgSender(); } } function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return super._msgData(); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol) pragma solidity ^0.8.0; import "./AddressUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Provides a function to batch together multiple calls in a single external call. * * _Available since v4.1._ */ abstract contract MulticallUpgradeable is Initializable { function __Multicall_init() internal onlyInitializing { } function __Multicall_init_unchained() internal onlyInitializing { } /** * @dev Receives and executes a batch of function calls on this contract. */ function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = _functionDelegateCall(address(this), data[i]); } return results; } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @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: Apache-2.0 pragma solidity ^0.8.11; // Helper interfaces import { IWETH } from "../interfaces/IWETH.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; library CurrencyTransferLib { /// @dev The address interpreted as native token of the chain. address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Transfers a given amount of currency. function transferCurrency( address _currency, address _from, address _to, uint256 _amount ) internal { if (_amount == 0) { return; } if (_currency == NATIVE_TOKEN) { safeTransferNativeToken(_to, _amount); } else { safeTransferERC20(_currency, _from, _to, _amount); } } /// @dev Transfers a given amount of currency. (With native token wrapping) function transferCurrencyWithWrapperAndBalanceCheck( address _currency, address _from, address _to, uint256 _amount, address _nativeTokenWrapper ) internal { if (_amount == 0) { return; } if (_currency == NATIVE_TOKEN) { if (_from == address(this)) { // withdraw from weth then transfer withdrawn native token to recipient IWETH(_nativeTokenWrapper).withdraw(_amount); safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper); } else if (_to == address(this)) { // store native currency in weth require(_amount == msg.value, "msg.value != amount"); IWETH(_nativeTokenWrapper).deposit{ value: _amount }(); } else { safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper); } } else { safeTransferERC20WithBalanceCheck(_currency, _from, _to, _amount); } } /// @dev Transfer `amount` of ERC20 token from `from` to `to`. function safeTransferERC20( address _currency, address _from, address _to, uint256 _amount ) internal { if (_from == _to) { return; } bool success = _from == address(this) ? IERC20Upgradeable(_currency).transfer(_to, _amount) : IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount); require(success, "currency transfer failed."); } /// @dev Transfer `amount` of ERC20 token from `from` to `to`. function safeTransferERC20WithBalanceCheck( address _currency, address _from, address _to, uint256 _amount ) internal { if (_from == _to) { return; } uint256 balBefore = IERC20Upgradeable(_currency).balanceOf(_to); bool success = _from == address(this) ? IERC20Upgradeable(_currency).transfer(_to, _amount) : IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount); uint256 balAfter = IERC20Upgradeable(_currency).balanceOf(_to); require(success && (balAfter == balBefore + _amount), "currency transfer failed."); } /// @dev Transfers `amount` of native token to `to`. function safeTransferNativeToken(address to, uint256 value) internal { // solhint-disable avoid-low-level-calls // slither-disable-next-line low-level-calls (bool success, ) = to.call{ value: value }(""); require(success, "native token transfer failed"); } /// @dev Transfers `amount` of native token to `to`. (With native token wrapping) function safeTransferNativeTokenWithWrapper( address to, uint256 value, address _nativeTokenWrapper ) internal { // solhint-disable avoid-low-level-calls // slither-disable-next-line low-level-calls (bool success, ) = to.call{ value: value }(""); if (!success) { IWETH(_nativeTokenWrapper).deposit{ value: value }(); require(IERC20Upgradeable(_nativeTokenWrapper).transfer(to, value), "transfer failed"); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; library FeeType { uint256 internal constant PRIMARY_SALE = 0; uint256 internal constant MARKET_SALE = 1; uint256 internal constant SPLIT = 2; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface ITWFee { function getFeeInfo(address _proxy, uint256 _type) external view returns (address recipient, uint256 bps); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IThirdwebContract { /// @dev Returns the module type of the contract. function contractType() external pure returns (bytes32); /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8); /// @dev Returns the metadata URI of the contract. function contractURI() external view returns (string memory); /** * @dev Sets contract URI for the storefront-level metadata of the contract. * Only module admin can call this function. */ function setContractURI(string calldata _uri) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IThirdwebPlatformFee { /// @dev Returns the platform fee bps and recipient. function getPlatformFeeInfo() external view returns (address platformFeeRecipient, uint16 platformFeeBps); /// @dev Lets a module admin update the fees on primary sales. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IThirdwebPrimarySale { /// @dev The adress that receives all primary sales value. function primarySaleRecipient() external view returns (address); /// @dev Lets a module admin set the default recipient of all primary sales. function setPrimarySaleRecipient(address _saleRecipient) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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 v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20PermitUpgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../utils/cryptography/draft-EIP712Upgradeable.sol"; import "../../../utils/cryptography/ECDSAUpgradeable.sol"; import "../../../utils/CountersUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping(address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal onlyInitializing { __EIP712_init_unchained(name, "1"); __ERC20Permit_init_unchained(name); } function __ERC20Permit_init_unchained(string memory) internal onlyInitializing { _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { CountersUpgradeable.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol) pragma solidity ^0.8.0; /** * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. * * _Available since v4.5._ */ interface IVotesUpgradeable { /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Returns the current amount of votes that `account` has. */ function getVotes(address account) external view returns (uint256); /** * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`). */ function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); /** * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`). * * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. * Votes that have not been delegated are still part of total supply, even though they would not participate in a * vote. */ function getPastTotalSupply(uint256 blockNumber) external view returns (uint256); /** * @dev Returns the delegate that `account` has chosen. */ function delegates(address account) external view returns (address); /** * @dev Delegates votes from the sender to `delegatee`. */ function delegate(address delegatee) external; /** * @dev Delegates votes from signer to `delegatee`. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCastUpgradeable { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) 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 onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } 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 virtual 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 virtual { 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 virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @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/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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 // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) 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 onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @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 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: Apache-2.0 pragma solidity ^0.8.11; interface IWETH { function deposit() external payable; function withdraw(uint256 amount) external; function transfer(address to, uint256 value) external returns (bool); }
@dev Collects and distributes the primary sale value of tokens being claimed.
function collectPrice( address _primarySaleRecipient, address _currency, uint256 _price ) internal { if (_price == 0) { return; } uint256 platformFees = (_price * platformFeeBps) / MAX_BPS; (address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.PRIMARY_SALE); uint256 twFee = (_price * twFeeBps) / MAX_BPS; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == _price, "must send total price."); } CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees); CurrencyTransferLib.transferCurrency(_currency, _msgSender(), twFeeRecipient, twFee); CurrencyTransferLib.transferCurrency( _currency, _msgSender(), _primarySaleRecipient, _price - platformFees - twFee ); }
409,466
[ 1, 28791, 471, 1015, 1141, 326, 3354, 272, 5349, 460, 434, 2430, 3832, 7516, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3274, 5147, 12, 203, 3639, 1758, 389, 8258, 30746, 18241, 16, 203, 3639, 1758, 389, 7095, 16, 203, 3639, 2254, 5034, 389, 8694, 203, 565, 262, 2713, 288, 203, 3639, 309, 261, 67, 8694, 422, 374, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 4072, 2954, 281, 273, 261, 67, 8694, 380, 4072, 14667, 38, 1121, 13, 342, 4552, 67, 38, 5857, 31, 203, 3639, 261, 2867, 2339, 14667, 18241, 16, 2254, 5034, 2339, 14667, 38, 1121, 13, 273, 12126, 4875, 14667, 18, 588, 14667, 966, 12, 2867, 12, 2211, 3631, 30174, 559, 18, 18864, 67, 5233, 900, 1769, 203, 3639, 2254, 5034, 2339, 14667, 273, 261, 67, 8694, 380, 2339, 14667, 38, 1121, 13, 342, 4552, 67, 38, 5857, 31, 203, 203, 3639, 309, 261, 67, 7095, 422, 13078, 5912, 5664, 18, 50, 12992, 67, 8412, 13, 288, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 389, 8694, 16, 315, 11926, 1366, 2078, 6205, 1199, 1769, 203, 3639, 289, 203, 203, 3639, 13078, 5912, 5664, 18, 13866, 7623, 24899, 7095, 16, 389, 3576, 12021, 9334, 4072, 14667, 18241, 16, 4072, 2954, 281, 1769, 203, 3639, 13078, 5912, 5664, 18, 13866, 7623, 24899, 7095, 16, 389, 3576, 12021, 9334, 2339, 14667, 18241, 16, 2339, 14667, 1769, 203, 3639, 13078, 5912, 5664, 18, 13866, 7623, 12, 203, 5411, 389, 7095, 16, 203, 5411, 389, 3576, 12021, 9334, 203, 5411, 389, 8258, 30746, 18241, 16, 203, 5411, 389, 8694, 300, 4072, 2954, 281, 300, 2339, 14667, 203, 3639, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.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'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; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- interface IToken { function transfer(address to, uint256 tokens) external returns (bool success); function burnTokens(uint256 _amount) external; function balanceOf(address tokenOwner) external view returns (uint256 balance); } contract Presale is Owned { using SafeMath for uint256; bool public isPresaleOpen; //@dev ERC20 token address and decimals address public tokenAddress; uint256 public tokenDecimals = 9; //@dev amount of tokens per ether 100 indicates 1 token per eth uint256 public tokenRatePerEth = 500_00; //@dev decimal for tokenRatePerEth, //2 means if you want 100 tokens per eth then set the rate as 100 + number of rateDecimals i.e => 10000 uint256 public rateDecimals = 2; //@dev max and min token buy limit per account uint256 public minEthLimit = 100 finney; uint256 public maxEthLimit = 1 ether; mapping(address => uint256) public usersInvestments; constructor() public { owner = msg.sender; } function startPresale() external onlyOwner{ require(!isPresaleOpen, "Presale is open"); isPresaleOpen = true; } function closePrsale() external onlyOwner{ require(isPresaleOpen, "Presale is not open yet."); isPresaleOpen = false; } function setTokenAddress(address token) external onlyOwner { require(tokenAddress == address(0), "Token address is already set."); require(token != address(0), "Token address zero not allowed."); tokenAddress = token; } function setTokenDecimals(uint256 decimals) external onlyOwner { tokenDecimals = decimals; } function setMinEthLimit(uint256 amount) external onlyOwner { minEthLimit = amount; } function setMaxEthLimit(uint256 amount) external onlyOwner { maxEthLimit = amount; } function setTokenRatePerEth(uint256 rate) external onlyOwner { tokenRatePerEth = rate; } function setRateDecimals(uint256 decimals) external onlyOwner { rateDecimals = decimals; } receive() external payable{ require(isPresaleOpen, "Presale is not open."); require( usersInvestments[msg.sender].add(msg.value) <= maxEthLimit && usersInvestments[msg.sender].add(msg.value) >= minEthLimit, "Installment Invalid." ); //@dev calculate the amount of tokens to transfer for the given eth uint256 tokenAmount = getTokensPerEth(msg.value); require(IToken(tokenAddress).transfer(msg.sender, tokenAmount), "Insufficient balance of presale contract!"); usersInvestments[msg.sender] = usersInvestments[msg.sender].add(msg.value); //@dev send received funds to the owner owner.transfer(msg.value); } function getTokensPerEth(uint256 amount) internal view returns(uint256) { return amount.mul(tokenRatePerEth).div( 10**(uint256(18).sub(tokenDecimals).add(rateDecimals)) ); } function burnUnsoldTokens() external onlyOwner { require(!isPresaleOpen, "You cannot burn tokens untitl the presale is closed."); IToken(tokenAddress).burnTokens(IToken(tokenAddress).balanceOf(address(this))); } function getUnsoldTokens() external onlyOwner { require(!isPresaleOpen, "You cannot get tokens until the presale is closed."); IToken(tokenAddress).transfer(owner, IToken(tokenAddress).balanceOf(address(this)) ); } }
@dev ERC20 token address and decimals@dev amount of tokens per ether 100 indicates 1 token per eth@dev decimal for tokenRatePerEth,2 means if you want 100 tokens per eth then set the rate as 100 + number of rateDecimals i.e => 10000@dev max and min token buy limit per account
contract Presale is Owned { using SafeMath for uint256; bool public isPresaleOpen; address public tokenAddress; uint256 public tokenDecimals = 9; uint256 public tokenRatePerEth = 500_00; uint256 public rateDecimals = 2; uint256 public minEthLimit = 100 finney; uint256 public maxEthLimit = 1 ether; mapping(address => uint256) public usersInvestments; constructor() public { owner = msg.sender; } function startPresale() external onlyOwner{ require(!isPresaleOpen, "Presale is open"); isPresaleOpen = true; } function closePrsale() external onlyOwner{ require(isPresaleOpen, "Presale is not open yet."); isPresaleOpen = false; } function setTokenAddress(address token) external onlyOwner { require(tokenAddress == address(0), "Token address is already set."); require(token != address(0), "Token address zero not allowed."); tokenAddress = token; } function setTokenDecimals(uint256 decimals) external onlyOwner { tokenDecimals = decimals; } function setMinEthLimit(uint256 amount) external onlyOwner { minEthLimit = amount; } function setMaxEthLimit(uint256 amount) external onlyOwner { maxEthLimit = amount; } function setTokenRatePerEth(uint256 rate) external onlyOwner { tokenRatePerEth = rate; } function setRateDecimals(uint256 decimals) external onlyOwner { rateDecimals = decimals; } receive() external payable{ require(isPresaleOpen, "Presale is not open."); require( usersInvestments[msg.sender].add(msg.value) <= maxEthLimit && usersInvestments[msg.sender].add(msg.value) >= minEthLimit, "Installment Invalid." ); uint256 tokenAmount = getTokensPerEth(msg.value); require(IToken(tokenAddress).transfer(msg.sender, tokenAmount), "Insufficient balance of presale contract!"); usersInvestments[msg.sender] = usersInvestments[msg.sender].add(msg.value); owner.transfer(msg.value); } function getTokensPerEth(uint256 amount) internal view returns(uint256) { return amount.mul(tokenRatePerEth).div( 10**(uint256(18).sub(tokenDecimals).add(rateDecimals)) ); } function burnUnsoldTokens() external onlyOwner { require(!isPresaleOpen, "You cannot burn tokens untitl the presale is closed."); IToken(tokenAddress).burnTokens(IToken(tokenAddress).balanceOf(address(this))); } function getUnsoldTokens() external onlyOwner { require(!isPresaleOpen, "You cannot get tokens until the presale is closed."); IToken(tokenAddress).transfer(owner, IToken(tokenAddress).balanceOf(address(this)) ); } }
1,738,637
[ 1, 654, 39, 3462, 1147, 1758, 471, 15105, 3844, 434, 2430, 1534, 225, 2437, 2130, 8527, 404, 1147, 1534, 13750, 6970, 364, 1147, 4727, 2173, 41, 451, 16, 22, 4696, 309, 1846, 2545, 2130, 2430, 1534, 13750, 1508, 444, 326, 4993, 487, 2130, 397, 1300, 434, 4993, 31809, 277, 18, 73, 516, 12619, 943, 471, 1131, 1147, 30143, 1800, 1534, 2236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 18346, 5349, 353, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 565, 1426, 1071, 353, 12236, 5349, 3678, 31, 203, 377, 203, 565, 1758, 1071, 1147, 1887, 31, 203, 565, 2254, 5034, 1071, 1147, 31809, 273, 2468, 31, 203, 377, 203, 565, 2254, 5034, 1071, 1147, 4727, 2173, 41, 451, 273, 6604, 67, 713, 31, 203, 565, 2254, 5034, 1071, 4993, 31809, 273, 576, 31, 203, 377, 203, 565, 2254, 5034, 1071, 1131, 41, 451, 3039, 273, 2130, 574, 82, 402, 31, 203, 565, 2254, 5034, 1071, 943, 41, 451, 3039, 273, 404, 225, 2437, 31, 203, 377, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 3677, 3605, 395, 1346, 31, 203, 377, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 377, 203, 565, 445, 787, 12236, 5349, 1435, 3903, 1338, 5541, 95, 203, 3639, 2583, 12, 5, 291, 12236, 5349, 3678, 16, 315, 12236, 5349, 353, 1696, 8863, 203, 540, 203, 3639, 353, 12236, 5349, 3678, 273, 638, 31, 203, 565, 289, 203, 377, 203, 565, 445, 1746, 2050, 87, 5349, 1435, 3903, 1338, 5541, 95, 203, 3639, 2583, 12, 291, 12236, 5349, 3678, 16, 315, 12236, 5349, 353, 486, 1696, 4671, 1199, 1769, 203, 540, 203, 3639, 353, 12236, 5349, 3678, 273, 629, 31, 203, 565, 289, 203, 377, 203, 565, 445, 22629, 1887, 12, 2867, 1147, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 2316, 1887, 422, 1758, 12, 20, 2 ]
pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ 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; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Pausable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale is Whitelist{ using SafeMath for uint256; // The token being sold MiniMeToken public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate = 6120; // Amount of tokens sold uint256 public tokensSold; //Star of the crowdsale uint256 startTime; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event buyx(address buyer, address contractAddr, uint256 amount); constructor(address _wallet, MiniMeToken _token, uint256 starttime) public{ require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; startTime = starttime; } function setCrowdsale(address _wallet, MiniMeToken _token, uint256 starttime) public{ require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; startTime = starttime; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * fallback function ***DO NOT OVERRIDE*** */ function () external whenNotPaused payable { emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public whenNotPaused payable { if ((tokensSold > 20884500000000000000000000 ) && (tokensSold <= 30791250000000000000000000)) { rate = 5967; } else if ((tokensSold > 30791250000000000000000000) && (tokensSold <= 39270000000000000000000000)) { rate = 5865; } else if ((tokensSold > 39270000000000000000000000) && (tokensSold <= 46856250000000000000000000)) { rate = 5610; } else if ((tokensSold > 46856250000000000000000000) && (tokensSold <= 35700000000000000000000000)) { rate = 5355; } else if (tokensSold > 35700000000000000000000000) { rate = 5100; } uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount); tokensSold = tokensSold.add(tokens); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } contract EmaCrowdSale is Crowdsale { uint256 public hardcap; uint256 public starttime; Crowdsale public csale; using SafeMath for uint256; constructor(address wallet, MiniMeToken token, uint256 startTime, uint256 cap) Crowdsale(wallet, token, starttime) public onlyOwner { hardcap = cap; starttime = startTime; setCrowdsale(wallet, token, startTime); } function tranferPresaleTokens(address investor, uint256 ammount)public onlyOwner{ tokensSold = tokensSold.add(ammount); token.transferFrom(this, investor, ammount); } function setTokenTransferState(bool state) public onlyOwner { token.changeController(this); token.enableTransfers(state); } function claim(address claimToken) public onlyOwner { token.changeController(this); token.claimTokens(claimToken); } function () external payable onlyWhitelisted whenNotPaused{ emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } } contract Controlled is Pausable { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } modifier onlyControllerorOwner { require((msg.sender == controller) || (msg.sender == owner)); _; } address public controller; constructor() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyControllerorOwner { controller = _newController; } } /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { using SafeMath for uint256; string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'V 1.0'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(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(address _from, address _to, uint256 _amount ) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo.add(_amount)); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyControllerorOwner whenNotPaused returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply.add(_amount) >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount)); updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount)); emit Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyControllerorOwner public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount)); updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount)); emit Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyControllerorOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) return checkpoints[checkpoints.length.sub(1)].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length.sub(1); while (max > min) { uint mid = (max.add(min).add(1)).div(2); if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid.sub(1); } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () public payable { /*require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));*/ revert(); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyControllerorOwner { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract EmaToken is MiniMeToken { constructor(address tokenfactory, address parenttoken, uint parentsnapshot, string tokenname, uint8 dec, string tokensymbol, bool transfersenabled) MiniMeToken(tokenfactory, parenttoken, parentsnapshot, tokenname, dec, tokensymbol, transfersenabled) public{ } } contract Configurator is Ownable { EmaToken public token = EmaToken(0xC3EE57Fa8eD253E3F214048879977265967AE745); EmaCrowdSale public crowdsale = EmaCrowdSale(0xAd97aF045F815d91621040809F863a5fb070B52d); address ownerWallet = 0x3046751e1d843748b4983D7bca58ECF6Ef1e5c77; address tokenfactory = 0xB74AA356913316ce49626527AE8543FFf23bB672; address fundsWallet = 0x3046751e1d843748b4983D7bca58ECF6Ef1e5c77; address incetivesPool = 0x95eac65414a6a650E2c71e3480AeEF0cF76392FA; address FoundersAndTeam = 0x88C952c4A8fc156b883318CdA8b4a5279d989391; address FuturePartners = 0x5B0333399E0D8F3eF1e5202b4eA4ffDdFD7a0382; address Contributors = 0xa02dfB73de485Ebd9d37CbA4583e916F3bA94CeE; address BountiesWal = 0xaB662f89A2c6e71BD8c7f754905cAaEC326BcdE7; uint256 public crowdSaleStart; function deploy() onlyOwner public{ owner = msg.sender; // crowdsale.transferOwnership(ownerWallet); // token.transferOwnership(ownerWallet); // token.changeController(this); token.generateTokens(crowdsale, 255000000000000000000000000); // Generate CrowdSale tokens token.generateTokens(incetivesPool, 115000000000000000000000000); //generate Incentives pool tokens token.generateTokens(FoundersAndTeam, 85000000000000000000000000); //generate Founders and team tokens token.generateTokens(FuturePartners, 40000000000000000000000000); //generate future partners tokens and contributors token.generateTokens(BountiesWal, 5000000000000000000000000); //generate contributors tokens token.changeController(EmaCrowdSale(crowdsale)); token.transferOwnership(ownerWallet); crowdsale.transferOwnership(ownerWallet); } }
The Token's name: e.g. DigixDAO Tokens
string public name;
170,782
[ 1, 1986, 3155, 1807, 508, 30, 425, 18, 75, 18, 11678, 697, 18485, 13899, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 540, 533, 1071, 508, 31, 1171, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts\interface\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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts\interface\Ownable.sol pragma solidity ^0.8.0; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "ERC20Ownable: 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), "ERC20Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts\interface\IUniswapAMM.sol pragma solidity >=0.5.0; 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; } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.2; 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; } // File: contracts\library\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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts\library\SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: contracts\interface\IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts\library\SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts\interface\IAntiBotBlacklist.sol pragma solidity ^0.8.0; interface IAntiBotBlacklist { function blacklistCheck(address suspect) external view returns (bool); function blacklistCheckExpirationTime(address suspect) external view returns (uint256); function addSuspect(address suspect, uint256 _expirationTime) external; function removeSuspect(address suspect) external; function addSuspectBatch( address[] memory _addresses, uint256 _expirationTime ) external; function removeSuspectBatch(address[] memory _addresses) external; event AddSuspect(address indexed suspect); event RemoveSuspect(address indexed suspect); } // File: contracts\util\AntiBotBlacklist.sol pragma solidity ^0.8.0; abstract contract AntiBotBlacklist is Ownable, IAntiBotBlacklist { using SafeMath for uint256; uint256 public blacklistLength; /** * @dev mapping store blacklist. address=>ExpirationTime */ mapping(address => uint256) blacklist; modifier antiBot(address _user) { require(blacklistCheck(_user), "user is in decentralized blacklist"); _; } modifier antiBots(address _user0, address _user1) { require(blacklistCheck(_user0), "user0 is in decentralized blacklist"); require(blacklistCheck(_user1), "user1 is in decentralized blacklist"); _; } /** * @dev check if the address is in the blacklist or not or expired */ function blacklistCheck(address suspect) public view override returns (bool) { return blacklist[suspect] < block.timestamp; } /** * @dev check if the address is in the blacklist or not */ function blacklistCheckExpirationTime(address suspect) external view override returns (uint256) { return blacklist[suspect]; } /** * @dev Add an address to the blacklist. Only the owner can add. Owner is the address of the Governance contract. */ function addSuspect(address _suspect, uint256 _expirationTime) external override onlyOwner { _addSuspectToBlackList(_suspect, _expirationTime); } /** * @dev Remove an address from the blacklist. Only the owner can remove. Owner is the address of the Governance contract. */ function removeSuspect(address suspect) external override onlyOwner { _removeSuspectToBlackList(suspect); } /** * @dev Add multi address to the blacklist. Only the owner can add. Owner is the address of the Governance contract. */ function addSuspectBatch( address[] memory _addresses, uint256 _expirationTime ) external override onlyOwner { require(_addresses.length > 0, "addresses is empty"); for (uint256 i = 0; i < _addresses.length; i++) { _addSuspectToBlackList(_addresses[i], _expirationTime); } } /** * @dev Remove multi address from the blacklist. Only the owner can remove. Owner is the address of the Governance contract. */ function removeSuspectBatch(address[] memory _addresses) external override onlyOwner { require(_addresses.length > 0, "addresses is empty"); for (uint256 i = 0; i < _addresses.length; i++) { _removeSuspectToBlackList(_addresses[i]); } } /** * @dev internal function to add address to blacklist. */ function _addSuspectToBlackList(address _suspect, uint256 _expirationTime) internal { require(_suspect != owner(), "the suspect cannot be owner"); require(blacklist[_suspect] == 0, "the suspect already exist"); blacklist[_suspect] = _expirationTime; blacklistLength = blacklistLength.add(1); emit AddSuspect(_suspect); } /** * @dev internal function to remove address from blacklist. */ function _removeSuspectToBlackList(address _suspect) internal { require(blacklist[_suspect] > 0, "suspect is not in blacklist"); delete blacklist[_suspect]; blacklistLength = blacklistLength.sub(1); emit RemoveSuspect(_suspect); } } // File: contracts\BTFAToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title TokenGeneratorMetadata * @author Create My Token (https://t.me/LemonCryptoDev) * @dev Implementation of the TokenGeneratorMetadata */ contract TokenGeneratorMetadata { string public constant _GENERATOR = "https://t.me/LemonCryptoDev"; string public constant _VERSION = "v1.0.0"; function generator() public pure returns (string memory) { return _GENERATOR; } function version() public pure returns (string memory) { return _VERSION; } } pragma solidity ^0.8.0; /** * @title BTFA_Token * @author Create My Token (https://t.me/LemonCryptoDev) * @dev Implementation of the BTFA_Token */ contract BTFA_Token is IERC20, AntiBotBlacklist, TokenGeneratorMetadata { using SafeMath for uint256; using Address for address; using SafeERC20 for IERC20; address dead = 0x000000000000000000000000000000000000dEaD; address zero = address(0); uint8 public constant _maxLiqFee = 10; uint8 public constant _maxTaxFee = 10; uint8 public constant _maxWalletFee = 10; uint256 public constant _minMxTxAmount = 1000 * 10**9; uint256 public constant _minMxSnipeAmount = 1000 * 10**9; uint256 public constant _minMxWalletAmount = 1000 * 10**9; 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 _isExcludedFromAntiSnipe; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 public _tTotal; uint256 private _rTotal; uint256 private _tFeeTotal; string public _name = "Banana Task Force Ape"; string public _symbol = "BTFA"; uint8 private _decimals = 9; uint8 public _buyTaxFee = 0; // Fee for Reflection in Buying uint8 public _sellTaxFee = 0; // Fee for Reflection in Selling uint8 public _taxFee = 0; // Fee for Reflection uint8 private _previousTaxFee = _taxFee; uint8 public _buyLiquidityFee = 0; // Fee for Liquidity in Buying uint8 public _sellLiquidityFee = 0; // Fee for Liquidity in Selling uint8 public _liquidityFee = 0; // Fee for Liquidity uint8 private _previousLiquidityFee = _liquidityFee; uint8 public _buyWalletFee = 0; // Fee to marketing/charity wallet in Buying uint8 public _sellWalletFee = 0; // Fee to marketing/charity wallet in Selling uint8 public _walletFee = 0; // Fee to marketing/charity wallet uint8 private _previousWalletFee = _walletFee; IUniswapV2Router02 public immutable _uniV2Router; address public immutable _uniV2Pair; address payable public _marketingWallet; bool _inSwapAndLiquify; bool public _swapAndLiquifyEnabled = true; uint256 public _maxTxAmount; uint256 public _maxWalletAmount; uint256 public _maxSnipeAmount; uint256 public _numTokensSellToAddToLiquidity; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap() { _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } modifier antiSnipe( address from, address to, uint256 amount ) { if (!_isExcludedFromAntiSnipe[from] && to == _uniV2Pair) { require( amount <= _maxSnipeAmount, "Exceeds the limited sell amount" ); } _; } constructor( uint256 maxSupply, address routerAddress, address marketingWallet, uint8 buyReflectionFee, uint8 buyWalletFee, uint8 buyLiquidityFee, uint8 sellReflectionFee, uint8 sellWalletFee, uint8 sellLiquidityFee ) payable { _tTotal = maxSupply; _rTotal = (MAX - (MAX % _tTotal)); _rOwned[_msgSender()] = _rTotal; require(marketingWallet != address(0), "INVALID MARKETING WALLET"); _marketingWallet = payable(marketingWallet); _maxTxAmount = _tTotal.mul(1).div(10**6); _maxSnipeAmount = _tTotal.mul(1).div(10**6); _maxWalletAmount = _tTotal.mul(1).div(10**4); _numTokensSellToAddToLiquidity = maxSupply.mul(1).div(10000); IUniswapV2Router02 uniV2Router = IUniswapV2Router02(routerAddress); // Create a uniswap pair for this new token _uniV2Pair = IUniswapV2Factory(uniV2Router.factory()).createPair( address(this), uniV2Router.WETH() ); // set the rest of the contract variables _uniV2Router = uniV2Router; _isExcludedFromFee[_msgSender()] = true; _isExcludedFromFee[dead] = true; _isExcludedFromFee[zero] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromAntiSnipe[_msgSender()] = true; _isExcludedFromAntiSnipe[address(this)] = true; require(buyReflectionFee <= _maxTaxFee, "Buy TF Error"); require(buyLiquidityFee <= _maxLiqFee, "Buy LF Error"); require(buyWalletFee <= _maxWalletFee, "Buy WF Error"); _buyTaxFee = buyReflectionFee; _buyLiquidityFee = buyLiquidityFee; _buyWalletFee = buyWalletFee; require(sellReflectionFee <= _maxTaxFee, "Buy TF Error"); require(sellLiquidityFee <= _maxLiqFee, "Buy LF Error"); require(sellWalletFee <= _maxWalletFee, "Buy WF Error"); _sellTaxFee = sellReflectionFee; _sellLiquidityFee = sellLiquidityFee; _sellWalletFee = sellWalletFee; 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 isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } 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, "Amt 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, "Amt must be less than tot refl"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require( !_isExcluded[account], "Account is already excluded from reward" ); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "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 excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function excludeFromAntiSnipe(address account) public onlyOwner { _isExcludedFromAntiSnipe[account] = true; } function includeInAntiSnipe(address account) public onlyOwner { _isExcludedFromAntiSnipe[account] = false; } function isExcludedFromAntiSnipe(address account) public view returns (bool) { return _isExcludedFromAntiSnipe[account]; } function setAllBuyFeePercent( uint8 taxFee, uint8 liquidityFee, uint8 walletFee ) external onlyOwner { require(taxFee >= 0 && taxFee <= _maxTaxFee, "TF error"); require(liquidityFee >= 0 && liquidityFee <= _maxLiqFee, "LF error"); require(walletFee >= 0 && walletFee <= _maxWalletFee, "WF error"); _buyTaxFee = taxFee; _buyLiquidityFee = liquidityFee; _buyWalletFee = walletFee; } function setAllSellFeePercent( uint8 taxFee, uint8 liquidityFee, uint8 walletFee ) external onlyOwner { require(taxFee >= 0 && taxFee <= _maxTaxFee, "TF error"); require(liquidityFee >= 0 && liquidityFee <= _maxLiqFee, "LF error"); require(walletFee >= 0 && walletFee <= _maxWalletFee, "WF error"); _sellTaxFee = taxFee; _sellLiquidityFee = liquidityFee; _sellWalletFee = walletFee; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner { require(maxTxAmount >= _minMxTxAmount, "The value is too small"); _maxTxAmount = maxTxAmount; } function setMaxSnipeAmount(uint256 maxSnipeAmount) external onlyOwner { require(maxSnipeAmount >= _minMxSnipeAmount, "The value is too small"); _maxSnipeAmount = maxSnipeAmount; } function setMaxWalletAmount(uint256 maxWalletAmount) external onlyOwner { require( maxWalletAmount >= _minMxWalletAmount, "The value is too small" ); _maxWalletAmount = maxWalletAmount; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { _swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setNumTokensSellToAddToLiquidity(uint256 amount) public onlyOwner { require(amount > 0, "The amount should be greater than zero"); require(amount < totalSupply(), "The amount should be less than total supply"); _numTokensSellToAddToLiquidity = amount; } function setMarketingWallet(address payable newMarketingWallet) external onlyOwner { require(newMarketingWallet != address(0), "ZERO ADDRESS"); _marketingWallet = newMarketingWallet; } //to recieve ETH from uniV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee + _walletFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0 && _walletFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousWalletFee = _walletFee; _taxFee = 0; _liquidityFee = 0; _walletFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _walletFee = _previousWalletFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from zero address"); require(spender != address(0), "ERC20: approve to zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private antiBots(from, to) antiSnipe(from, to, amount) { require(from != address(0), "ERC20: transfer from zero address"); require(to != address(0), "ERC20: transfer to zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); if ( from != owner() && to != owner() && to != address(0) && to != dead && to != _uniV2Pair ) { uint256 contractBalanceRecepient = balanceOf(to); require( contractBalanceRecepient + amount <= _maxWalletAmount, "Exceeds maximum wallet amount" ); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (!_inSwapAndLiquify && to == _uniV2Pair && _swapAndLiquifyEnabled) { if (contractTokenBalance >= _numTokensSellToAddToLiquidity) { contractTokenBalance = _numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } if (takeFee) { if (from == _uniV2Pair) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee; _walletFee = _buyWalletFee; } else if (to == _uniV2Pair) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee; _walletFee = _sellWalletFee; } else { takeFee = false; } } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { //This needs to be distributed among burn, wallet and liquidity //burn uint8 totFee = _walletFee + _liquidityFee; uint256 spentAmount = 0; if (_walletFee != 0) { spentAmount = contractTokenBalance.div(totFee).mul(_walletFee); _tokenTransferNoFee(address(this), _marketingWallet, spentAmount); } if (_liquidityFee != 0) { contractTokenBalance = contractTokenBalance.sub(spentAmount); // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForETH(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } } function buyBackTokens(uint256 amount) private lockTheSwap { if (amount > 0) { swapETHForTokens(amount); } } function swapTokensForETH(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniV2Router.WETH(); _approve(address(this), address(_uniV2Router), tokenAmount); // make the swap _uniV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp.add(300) ); } function swapETHForTokens(uint256 amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = _uniV2Router.WETH(); path[1] = address(this); // make the swap _uniV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: amount }( 0, // accept any amount of Tokens path, dead, // Burn address block.timestamp.add(300) ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(_uniV2Router), tokenAmount); // add the liquidity _uniV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable dead, block.timestamp.add(300) ); } //this method is responsible for taking all fee, if takeFee is true 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 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _tokenTransferNoFee( address sender, address recipient, uint256 amount ) private { _rOwned[sender] = _rOwned[sender].sub(amount); _rOwned[recipient] = _rOwned[recipient].add(amount); if (_isExcluded[sender]) { _tOwned[sender] = _tOwned[sender].sub(amount); } if (_isExcluded[recipient]) { _tOwned[recipient] = _tOwned[recipient].add(amount); } emit Transfer(sender, recipient, amount); } function recoverToken(address tokenAddress, uint256 tokenAmount) public onlyOwner { // do not allow recovering self token require(tokenAddress != address(this), "Self withdraw"); IERC20(tokenAddress).transfer(owner(), tokenAmount); } }
* @dev internal function to add address to blacklist./
function _addSuspectToBlackList(address _suspect, uint256 _expirationTime) internal { require(_suspect != owner(), "the suspect cannot be owner"); require(blacklist[_suspect] == 0, "the suspect already exist"); blacklist[_suspect] = _expirationTime; blacklistLength = blacklistLength.add(1); emit AddSuspect(_suspect); }
14,540,058
[ 1, 7236, 445, 358, 527, 1758, 358, 11709, 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 ]
[ 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, 389, 1289, 55, 407, 1181, 774, 13155, 682, 12, 2867, 389, 87, 407, 1181, 16, 2254, 5034, 389, 19519, 950, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2583, 24899, 87, 407, 1181, 480, 3410, 9334, 315, 5787, 11375, 1181, 2780, 506, 3410, 8863, 203, 3639, 2583, 12, 22491, 63, 67, 87, 407, 1181, 65, 422, 374, 16, 315, 5787, 11375, 1181, 1818, 1005, 8863, 203, 3639, 11709, 63, 67, 87, 407, 1181, 65, 273, 389, 19519, 950, 31, 203, 3639, 11709, 1782, 273, 11709, 1782, 18, 1289, 12, 21, 1769, 203, 3639, 3626, 1436, 55, 407, 1181, 24899, 87, 407, 1181, 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 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.11; import "hardhat/console.sol"; import { ERC20 } from "./lib/ERC20.sol"; import { VestedERC20 } from "./VestedERC20.sol"; import { ClonesWithCallData } from "./lib/ClonesWithCallData.sol"; /// @title VestedERC20Factory /// @author zefram.eth /// @notice Factory for deploying VestedERC20 contracts cheaply contract VestedERC20Factory { /// ----------------------------------------------------------------------- /// Library usage /// ----------------------------------------------------------------------- using ClonesWithCallData for address; /// ----------------------------------------------------------------------- /// Errors /// ----------------------------------------------------------------------- error Error_InvalidTimeRange(); /// ----------------------------------------------------------------------- /// Events /// ----------------------------------------------------------------------- event DeployVestedERC20(address vestedERC0); /// ----------------------------------------------------------------------- /// Immutable parameters /// ----------------------------------------------------------------------- /// @notice The VestedERC20 used as the template for all clones created VestedERC20 public immutable implementation; constructor(VestedERC20 implementation_) { implementation = implementation_; } /// @notice Creates a VestedERC20 contract /// @dev Uses a modified minimal proxy contract that stores immutable parameters in code and /// passes them in through calldata. See ClonesWithCallData. /// @param name The name of the VestedERC20 token /// @param symbol The symbol of the VestedERC20 token /// @param decimals The number of decimals used by the VestedERC20 token /// @param underlying The ERC20 token that is vested /// @param startTimestamp The start time of the vest, Unix timestamp in seconds /// @param endTimestamp The end time of the vest, must be greater than startTimestamp, Unix timestamp in seconds /// @return The created VestedERC20 contract function createVestedERC20( bytes32 name, bytes32 symbol, uint8 decimals, address underlying, uint64 startTimestamp, uint64 endTimestamp ) external returns (VestedERC20) { if (endTimestamp <= startTimestamp) { revert Error_InvalidTimeRange(); } bytes memory ptr = new bytes(101); assembly { mstore(add(ptr, 0x20), name) mstore(add(ptr, 0x40), symbol) mstore8(add(ptr, 0x60), decimals) mstore(add(ptr, 0x61), shl(0x60, underlying)) mstore(add(ptr, 0x75), shl(0xc0, startTimestamp)) mstore(add(ptr, 0x7d), shl(0xc0, endTimestamp)) } address newAddress = address(implementation).cloneWithCallDataProvision(ptr); emit DeployVestedERC20(newAddress); return VestedERC20(newAddress); } }
@title VestedERC20Factory @author zefram.eth @notice Factory for deploying VestedERC20 contracts cheaply
contract VestedERC20Factory { using ClonesWithCallData for address; error Error_InvalidTimeRange(); event DeployVestedERC20(address vestedERC0); VestedERC20 public immutable implementation; import { ERC20 } from "./lib/ERC20.sol"; import { VestedERC20 } from "./VestedERC20.sol"; import { ClonesWithCallData } from "./lib/ClonesWithCallData.sol"; constructor(VestedERC20 implementation_) { implementation = implementation_; } function createVestedERC20( bytes32 name, bytes32 symbol, uint8 decimals, address underlying, uint64 startTimestamp, uint64 endTimestamp ) external returns (VestedERC20) { if (endTimestamp <= startTimestamp) { revert Error_InvalidTimeRange(); } bytes memory ptr = new bytes(101); assembly { mstore(add(ptr, 0x20), name) mstore(add(ptr, 0x40), symbol) mstore8(add(ptr, 0x60), decimals) mstore(add(ptr, 0x61), shl(0x60, underlying)) mstore(add(ptr, 0x75), shl(0xc0, startTimestamp)) mstore(add(ptr, 0x7d), shl(0xc0, endTimestamp)) } address newAddress = address(implementation).cloneWithCallDataProvision(ptr); emit DeployVestedERC20(newAddress); return VestedERC20(newAddress); } function createVestedERC20( bytes32 name, bytes32 symbol, uint8 decimals, address underlying, uint64 startTimestamp, uint64 endTimestamp ) external returns (VestedERC20) { if (endTimestamp <= startTimestamp) { revert Error_InvalidTimeRange(); } bytes memory ptr = new bytes(101); assembly { mstore(add(ptr, 0x20), name) mstore(add(ptr, 0x40), symbol) mstore8(add(ptr, 0x60), decimals) mstore(add(ptr, 0x61), shl(0x60, underlying)) mstore(add(ptr, 0x75), shl(0xc0, startTimestamp)) mstore(add(ptr, 0x7d), shl(0xc0, endTimestamp)) } address newAddress = address(implementation).cloneWithCallDataProvision(ptr); emit DeployVestedERC20(newAddress); return VestedERC20(newAddress); } function createVestedERC20( bytes32 name, bytes32 symbol, uint8 decimals, address underlying, uint64 startTimestamp, uint64 endTimestamp ) external returns (VestedERC20) { if (endTimestamp <= startTimestamp) { revert Error_InvalidTimeRange(); } bytes memory ptr = new bytes(101); assembly { mstore(add(ptr, 0x20), name) mstore(add(ptr, 0x40), symbol) mstore8(add(ptr, 0x60), decimals) mstore(add(ptr, 0x61), shl(0x60, underlying)) mstore(add(ptr, 0x75), shl(0xc0, startTimestamp)) mstore(add(ptr, 0x7d), shl(0xc0, endTimestamp)) } address newAddress = address(implementation).cloneWithCallDataProvision(ptr); emit DeployVestedERC20(newAddress); return VestedERC20(newAddress); } }
12,545,507
[ 1, 58, 3149, 654, 39, 3462, 1733, 225, 998, 10241, 1940, 18, 546, 225, 7822, 364, 7286, 310, 776, 3149, 654, 39, 3462, 20092, 19315, 69, 1283, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 776, 3149, 654, 39, 3462, 1733, 288, 203, 203, 225, 1450, 3905, 5322, 1190, 1477, 751, 364, 1758, 31, 203, 203, 203, 225, 555, 1068, 67, 1941, 950, 2655, 5621, 203, 203, 203, 225, 871, 7406, 58, 3149, 654, 39, 3462, 12, 2867, 331, 3149, 654, 39, 20, 1769, 203, 203, 203, 225, 776, 3149, 654, 39, 3462, 1071, 11732, 4471, 31, 203, 203, 203, 5666, 288, 4232, 39, 3462, 289, 628, 25165, 2941, 19, 654, 39, 3462, 18, 18281, 14432, 203, 5666, 288, 776, 3149, 654, 39, 3462, 289, 628, 25165, 58, 3149, 654, 39, 3462, 18, 18281, 14432, 203, 5666, 288, 3905, 5322, 1190, 1477, 751, 289, 628, 25165, 2941, 19, 2009, 5322, 1190, 1477, 751, 18, 18281, 14432, 203, 225, 3885, 12, 58, 3149, 654, 39, 3462, 4471, 67, 13, 288, 203, 565, 4471, 273, 4471, 67, 31, 203, 225, 289, 203, 203, 225, 445, 752, 58, 3149, 654, 39, 3462, 12, 203, 565, 1731, 1578, 508, 16, 203, 565, 1731, 1578, 3273, 16, 203, 565, 2254, 28, 15105, 16, 203, 565, 1758, 6808, 16, 203, 565, 2254, 1105, 787, 4921, 16, 203, 565, 2254, 1105, 679, 4921, 203, 225, 262, 3903, 1135, 261, 58, 3149, 654, 39, 3462, 13, 288, 203, 565, 309, 261, 409, 4921, 1648, 787, 4921, 13, 288, 203, 1377, 15226, 1068, 67, 1941, 950, 2655, 5621, 203, 565, 289, 203, 203, 565, 1731, 3778, 6571, 273, 394, 1731, 12, 15168, 1769, 203, 565, 19931, 288, 203, 1377, 312, 2233, 12, 1289, 12, 6723, 16, 374, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-04-13 */ // SPDX-License-Identifier: UNLICENSED // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // 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) } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/interfaces/IERC20.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; // 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/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(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); _afterTokenTransfer(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 from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @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. * - `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 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (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/ERC721A.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). * * Assumes that an owner cannot have more than the 2**128 (max value of uint128) of supply */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex = 0; // 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 override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert('ERC721A: unable to determine the owner of token'); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token'); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @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); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), 'ERC721A: token already minted'); require(quantity > 0, 'ERC721A: quantity must be greater 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous 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('ERC721A: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/nnft.sol pragma solidity ^0.8.8; contract PixelMoonbird is ERC721A, Ownable { using Strings for uint256; uint256 public constant maxSupply = 2000; uint256 public constant PUBLIC_SALE_PRICE = 0.001 ether; uint256 public publicSaleEpoch; string public baseURI; string public notRevealedUri; mapping(address => uint256) public usedAddresses; bool public revealed = true; event Revealed(uint256 _tokenId); constructor() ERC721A("PixelMoonbird", "PixelMoonbird") { } function tokenURI(uint256 tokenId) public view override(ERC721A) returns (string memory) { require(_exists(tokenId), "Nonexistent token"); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = baseURI; return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(),".json")) : ""; } function Mint(uint256 count) external payable { require(msg.value >= PUBLIC_SALE_PRICE * count, "Ether value sent is below the price"); require(totalSupply() + count <= maxSupply, "Cannot Exceeds max supply"); require(usedAddresses[msg.sender] + count <= 5, "max per wallet reached"); require(count > 0 && count <= 5, "You can drop minimum 1, maximum 2 NFTs"); usedAddresses[msg.sender] += count; _mint(msg.sender, count); } function reservedMint(address _addrs, uint256 count) public onlyOwner { require(count <= maxSupply, "Not enough NFTs left"); _mint(_addrs, count); } /** * @dev Used by public mint functions and by owner functions. * Can only be called internally by other functions. */ function _mint(address to, uint256 count) internal virtual returns (uint256){ _safeMint(to, count); return count; } function reveal() public onlyOwner { revealed = true; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } }
File: contracts/nnft.sol
contract PixelMoonbird is ERC721A, Ownable { using Strings for uint256; uint256 public constant maxSupply = 2000; uint256 public constant PUBLIC_SALE_PRICE = 0.001 ether; uint256 public publicSaleEpoch; string public baseURI; string public notRevealedUri; mapping(address => uint256) public usedAddresses; bool public revealed = true; event Revealed(uint256 _tokenId); constructor() ERC721A("PixelMoonbird", "PixelMoonbird") function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } pragma solidity ^0.8.8; { } function tokenURI(uint256 tokenId) public view override(ERC721A) returns (string memory) { require(_exists(tokenId), "Nonexistent token"); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = baseURI; return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(),".json")) : ""; } function tokenURI(uint256 tokenId) public view override(ERC721A) returns (string memory) { require(_exists(tokenId), "Nonexistent token"); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = baseURI; return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(),".json")) : ""; } function Mint(uint256 count) external payable { require(msg.value >= PUBLIC_SALE_PRICE * count, "Ether value sent is below the price"); require(totalSupply() + count <= maxSupply, "Cannot Exceeds max supply"); require(usedAddresses[msg.sender] + count <= 5, "max per wallet reached"); require(count > 0 && count <= 5, "You can drop minimum 1, maximum 2 NFTs"); usedAddresses[msg.sender] += count; _mint(msg.sender, count); } function reservedMint(address _addrs, uint256 count) public onlyOwner { require(count <= maxSupply, "Not enough NFTs left"); _mint(_addrs, count); } function _mint(address to, uint256 count) internal virtual returns (uint256){ _safeMint(to, count); return count; } function reveal() public onlyOwner { revealed = true; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } }
5,748,129
[ 1, 812, 30, 20092, 19, 9074, 1222, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 26070, 16727, 265, 31245, 353, 4232, 39, 27, 5340, 37, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 225, 2254, 5034, 1071, 5381, 943, 3088, 1283, 273, 16291, 31, 203, 225, 2254, 5034, 1071, 5381, 17187, 67, 5233, 900, 67, 7698, 1441, 273, 374, 18, 11664, 225, 2437, 31, 203, 203, 225, 2254, 5034, 1071, 1071, 30746, 14638, 31, 203, 203, 203, 225, 533, 1071, 1026, 3098, 31, 203, 225, 533, 1071, 486, 426, 537, 18931, 3006, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1399, 7148, 31, 203, 203, 225, 1426, 1071, 283, 537, 18931, 273, 638, 31, 203, 203, 225, 871, 868, 537, 18931, 12, 11890, 5034, 389, 2316, 548, 1769, 203, 203, 225, 3885, 1435, 203, 565, 4232, 39, 27, 5340, 37, 2932, 9037, 16727, 265, 31245, 3113, 315, 9037, 16727, 265, 31245, 7923, 203, 565, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 203, 565, 445, 389, 5205, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 28, 31, 203, 203, 203, 203, 225, 288, 203, 225, 289, 203, 203, 282, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 2 ]
// SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "./base/ModuleManager.sol"; import "./base/OwnerManager.sol"; import "./base/FallbackManager.sol"; import "./base/GuardManager.sol"; import "./common/EtherPaymentFallback.sol"; import "./common/Singleton.sol"; import "./common/SignatureDecoder.sol"; import "./common/SecuredTokenTransfer.sol"; import "./common/StorageAccessible.sol"; import "./interfaces/ISignatureValidator.sol"; import "./external/GnosisSafeMath.sol"; /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract GnosisSafe is EtherPaymentFallback, Singleton, ModuleManager, OwnerManager, SignatureDecoder, SecuredTokenTransfer, ISignatureValidatorConstants, FallbackManager, StorageAccessible, GuardManager { using GnosisSafeMath for uint256; string public constant VERSION = "1.3.0"; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)" // ); bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8; event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler); event ApproveHash(bytes32 indexed approvedHash, address indexed owner); event SignMsg(bytes32 indexed msgHash); event ExecutionFailure(bytes32 txHash, uint256 payment); event ExecutionSuccess(bytes32 txHash, uint256 payment); uint256 public nonce; bytes32 private _deprecatedDomainSeparator; // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners mapping(bytes32 => uint256) public signedMessages; // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners mapping(address => mapping(bytes32 => uint256)) public approvedHashes; // This constructor ensures that this contract can only be used as a master copy for Proxy contracts constructor() { // By setting the threshold it is not possible to call setup anymore, // so we create a Safe with 0 owners and threshold 1. // This is an unusable Safe, perfect for the singleton threshold = 1; } /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. /// @param to Contract address for optional delegate call. /// @param data Data payload for optional delegate call. /// @param fallbackHandler Handler for fallback calls to this contract /// @param paymentToken Token that should be used for the payment (0 is ETH) /// @param payment Value that should be paid /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin) function setup( address[] calldata _owners, uint256 _threshold, address to, bytes calldata data, address fallbackHandler, address paymentToken, uint256 payment, address payable paymentReceiver ) external { // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice setupOwners(_owners, _threshold); if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler); // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules setupModules(to, data); if (payment > 0) { // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself) // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment handlePayment(payment, 0, 1, paymentToken, paymentReceiver); } emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler); } /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. /// Note: The fees are always transferred, even if the user transaction fails. /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @param safeTxGas Gas that should be used for the Safe transaction. /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Gas price that should be used for the payment calculation. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) function execTransaction( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures ) public payable virtual returns (bool success) { bytes32 txHash; // Use scope here to limit variable lifetime and prevent `stack too deep` errors { bytes memory txHashData = encodeTransactionData( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info nonce ); // Increase nonce and execute transaction. nonce++; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures); } address guard = getGuard(); { if (guard != address(0)) { Guard(guard).checkTransaction( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info signatures, msg.sender ); } } // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500) // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150 require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010"); // Use scope here to limit variable lifetime and prevent `stack too deep` errors { uint256 gasUsed = gasleft(); // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas) // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas); gasUsed = gasUsed.sub(gasleft()); // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert require(success || safeTxGas != 0 || gasPrice != 0, "GS013"); // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls uint256 payment = 0; if (gasPrice > 0) { payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver); } if (success) emit ExecutionSuccess(txHash, payment); else emit ExecutionFailure(txHash, payment); } { if (guard != address(0)) { Guard(guard).checkAfterExecution(txHash, success); } } } function handlePayment( uint256 gasUsed, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver ) private returns (uint256 payment) { // solhint-disable-next-line avoid-tx-origin address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver; if (gasToken == address(0)) { // For ETH we will only adjust the gas price to not be higher than the actual used gas price payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice); require(receiver.send(payment), "GS011"); } else { payment = gasUsed.add(baseGas).mul(gasPrice); require(transferToken(gasToken, receiver, payment), "GS012"); } } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. */ function checkSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures ) public view { // Load threshold to avoid multiple storage loads uint256 _threshold = threshold; // Check that a threshold is set require(_threshold > 0, "GS001"); checkNSignatures(dataHash, data, signatures, _threshold); } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. * @param requiredSignatures Amount of required valid signatures. */ function checkNSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures ) public view { // Check that the provided signature data is not too short require(signatures.length >= requiredSignatures.mul(65), "GS020"); // There cannot be an owner with address 0. address lastOwner = address(0); address currentOwner; uint8 v; bytes32 r; bytes32 s; uint256 i; for (i = 0; i < requiredSignatures; i++) { (v, r, s) = signatureSplit(signatures, i); if (v == 0) { // If v is 0 then it is a contract signature // When handling contract signatures the address of the contract is encoded into r currentOwner = address(uint160(uint256(r))); // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes // This check is not completely accurate, since it is possible that more signatures than the threshold are send. // Here we only check that the pointer is not pointing inside the part that is being processed require(uint256(s) >= requiredSignatures.mul(65), "GS021"); // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes) require(uint256(s).add(32) <= signatures.length, "GS022"); // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length uint256 contractSignatureLen; // solhint-disable-next-line no-inline-assembly assembly { contractSignatureLen := mload(add(add(signatures, s), 0x20)) } require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023"); // Check signature bytes memory contractSignature; // solhint-disable-next-line no-inline-assembly assembly { // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s contractSignature := add(add(signatures, s), 0x20) } require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024"); } else if (v == 1) { // If v is 1 then it is an approved hash // When handling approved hashes the address of the approver is encoded into r currentOwner = address(uint160(uint256(r))); // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025"); } else if (v > 30) { // If v > 30 then default va (27,28) has been adjusted for eth_sign flow // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover currentOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s); } else { // Default is the ecrecover flow with the provided data hash // Use ecrecover with the messageHash for EOA signatures currentOwner = ecrecover(dataHash, v, r, s); } require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026"); lastOwner = currentOwner; } } /// @dev Allows to estimate a Safe transaction. /// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data. /// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction` /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs). /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version. function requiredTxGas( address to, uint256 value, bytes calldata data, Enum.Operation operation ) external returns (uint256) { uint256 startGas = gasleft(); // We don't provide an error message here, as we use it to return the estimate require(execute(to, value, data, operation, gasleft())); uint256 requiredGas = startGas - gasleft(); // Convert response to string and return via error message revert(string(abi.encodePacked(requiredGas))); } /** * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature. * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract. */ function approveHash(bytes32 hashToApprove) external { require(owners[msg.sender] != address(0), "GS030"); approvedHashes[msg.sender][hashToApprove] = 1; emit ApproveHash(hashToApprove, msg.sender); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } function domainSeparator() public view returns (bytes32) { return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this)); } /// @dev Returns the bytes that are hashed to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Gas that should be used for the safe transaction. /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash bytes. function encodeTransactionData( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes memory) { bytes32 safeTxHash = keccak256( abi.encode( SAFE_TX_TYPEHASH, to, value, keccak256(data), operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce ) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash); } /// @dev Returns hash to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Fas that should be used for the safe transaction. /// @param baseGas Gas costs for data used to trigger the safe transaction. /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash. function getTransactionHash( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes32) { return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce)); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; /// @title Executor - A contract that can execute transactions /// @author Richard Meissner - <[email protected]> contract Executor { function execute( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txGas ) internal returns (bool success) { if (operation == Enum.Operation.DelegateCall) { // solhint-disable-next-line no-inline-assembly assembly { success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0) } } else { // solhint-disable-next-line no-inline-assembly assembly { success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) } } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/SelfAuthorized.sol"; /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract FallbackManager is SelfAuthorized { event ChangedFallbackHandler(address handler); // keccak256("fallback_manager.handler.address") bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5; function internalSetFallbackHandler(address handler) internal { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, handler) } } /// @dev Allows to add a contract to handle fallback calls. /// Only fallback calls without value and with data will be forwarded. /// This can only be done via a Safe transaction. /// @param handler contract to handle fallbacks calls. function setFallbackHandler(address handler) public authorized { internalSetFallbackHandler(handler); emit ChangedFallbackHandler(handler); } // solhint-disable-next-line payable-fallback,no-complex-fallback fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { let handler := sload(slot) if iszero(handler) { return(0, 0) } calldatacopy(0, 0, calldatasize()) // The msg.sender address is shifted to the left by 12 bytes to remove the padding // Then the address without padding is stored right after the calldata mstore(calldatasize(), shl(96, caller())) // Add 20 bytes for the address appended add the end let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0) returndatacopy(0, 0, returndatasize()) if iszero(success) { revert(0, returndatasize()) } return(0, returndatasize()) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; import "../common/SelfAuthorized.sol"; interface Guard { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; } /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract GuardManager is SelfAuthorized { event ChangedGuard(address guard); // keccak256("guard_manager.guard.address") bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8; /// @dev Set a guard that checks transactions before execution /// @param guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address guard) external authorized { bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, guard) } emit ChangedGuard(guard); } function getGuard() internal view returns (address guard) { bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { guard := sload(slot) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; import "../common/SelfAuthorized.sol"; import "./Executor.sol"; /// @title Module Manager - A contract that manages modules that can execute transactions via this contract /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract ModuleManager is SelfAuthorized, Executor { event EnabledModule(address module); event DisabledModule(address module); event ExecutionFromModuleSuccess(address indexed module); event ExecutionFromModuleFailure(address indexed module); address internal constant SENTINEL_MODULES = address(0x1); mapping(address => address) internal modules; function setupModules(address to, bytes memory data) internal { require(modules[SENTINEL_MODULES] == address(0), "GS100"); modules[SENTINEL_MODULES] = SENTINEL_MODULES; if (to != address(0)) // Setup has to complete successfully or transaction fails. require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000"); } /// @dev Allows to add a module to the whitelist. /// This can only be done via a Safe transaction. /// @notice Enables the module `module` for the Safe. /// @param module Module to be whitelisted. function enableModule(address module) public authorized { // Module address cannot be null or sentinel. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); // Module cannot be added twice. require(modules[module] == address(0), "GS102"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module); } /// @dev Allows to remove a module from the whitelist. /// This can only be done via a Safe transaction. /// @notice Disables the module `module` for the Safe. /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(address prevModule, address module) public authorized { // Validate module address and check that it corresponds to module index. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); require(modules[prevModule] == module, "GS103"); modules[prevModule] = modules[module]; modules[module] = address(0); emit DisabledModule(module); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule( address to, uint256 value, bytes memory data, Enum.Operation operation ) public virtual returns (bool success) { // Only whitelisted modules are allowed. require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104"); // Execute transaction without further confirmations. success = execute(to, value, data, operation, gasleft()); if (success) emit ExecutionFromModuleSuccess(msg.sender); else emit ExecutionFromModuleFailure(msg.sender); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModuleReturnData( address to, uint256 value, bytes memory data, Enum.Operation operation ) public returns (bool success, bytes memory returnData) { success = execTransactionFromModule(to, value, data, operation); // solhint-disable-next-line no-inline-assembly assembly { // Load free memory location let ptr := mload(0x40) // We allocate memory for the return data by setting the free memory location to // current free memory location + data size + 32 bytes for data size value mstore(0x40, add(ptr, add(returndatasize(), 0x20))) // Store the size mstore(ptr, returndatasize()) // Store the data returndatacopy(add(ptr, 0x20), 0, returndatasize()) // Point the return data to the correct memory location returnData := ptr } } /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) public view returns (bool) { return SENTINEL_MODULES != module && modules[module] != address(0); } /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) { // Init array with max page size array = new address[](pageSize); // Populate return array uint256 moduleCount = 0; address currentModule = modules[start]; while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount++; } next = currentModule; // Set correct size of returned array // solhint-disable-next-line no-inline-assembly assembly { mstore(array, moduleCount) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/SelfAuthorized.sol"; /// @title OwnerManager - Manages a set of owners and a threshold to perform actions. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract OwnerManager is SelfAuthorized { event AddedOwner(address owner); event RemovedOwner(address owner); event ChangedThreshold(uint256 threshold); address internal constant SENTINEL_OWNERS = address(0x1); mapping(address => address) internal owners; uint256 internal ownerCount; uint256 internal threshold; /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. function setupOwners(address[] memory _owners, uint256 _threshold) internal { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "GS200"); // Validate that threshold is smaller than number of added owners. require(_threshold <= _owners.length, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); // Initializing Safe owners. address currentOwner = SENTINEL_OWNERS; for (uint256 i = 0; i < _owners.length; i++) { // Owner address cannot be null. address owner = _owners[i]; require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[currentOwner] = owner; currentOwner = owner; } owners[currentOwner] = SENTINEL_OWNERS; ownerCount = _owners.length; threshold = _threshold; } /// @dev Allows to add a new owner to the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`. /// @param owner New owner address. /// @param _threshold New threshold. function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[owner] = owners[SENTINEL_OWNERS]; owners[SENTINEL_OWNERS] = owner; ownerCount++; emit AddedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to remove an owner from the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`. /// @param prevOwner Owner that pointed to the owner to be removed in the linked list /// @param owner Owner address to be removed. /// @param _threshold New threshold. function removeOwner( address prevOwner, address owner, uint256 _threshold ) public authorized { // Only allow to remove an owner, if threshold can still be reached. require(ownerCount - 1 >= _threshold, "GS201"); // Validate owner address and check that it corresponds to owner index. require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == owner, "GS205"); owners[prevOwner] = owners[owner]; owners[owner] = address(0); ownerCount--; emit RemovedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to swap/replace an owner from the Safe with another address. /// This can only be done via a Safe transaction. /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`. /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list /// @param oldOwner Owner address to be replaced. /// @param newOwner New owner address. function swapOwner( address prevOwner, address oldOwner, address newOwner ) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203"); // No duplicate owners allowed. require(owners[newOwner] == address(0), "GS204"); // Validate oldOwner address and check that it corresponds to owner index. require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == oldOwner, "GS205"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = address(0); emit RemovedOwner(oldOwner); emit AddedOwner(newOwner); } /// @dev Allows to update the number of required confirmations by Safe owners. /// This can only be done via a Safe transaction. /// @notice Changes the threshold of the Safe to `_threshold`. /// @param _threshold New threshold. function changeThreshold(uint256 _threshold) public authorized { // Validate that threshold is smaller than number of owners. require(_threshold <= ownerCount, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); threshold = _threshold; emit ChangedThreshold(threshold); } function getThreshold() public view returns (uint256) { return threshold; } function isOwner(address owner) public view returns (bool) { return owner != SENTINEL_OWNERS && owners[owner] != address(0); } /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() public view returns (address[] memory) { address[] memory array = new address[](ownerCount); // populate return array uint256 index = 0; address currentOwner = owners[SENTINEL_OWNERS]; while (currentOwner != SENTINEL_OWNERS) { array[index] = currentOwner; currentOwner = owners[currentOwner]; index++; } return array; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation {Call, DelegateCall} } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments /// @author Richard Meissner - <[email protected]> contract EtherPaymentFallback { event SafeReceived(address indexed sender, uint256 value); /// @dev Fallback function accepts Ether transactions. receive() external payable { emit SafeReceived(msg.sender, msg.value); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SecuredTokenTransfer - Secure token transfer /// @author Richard Meissner - <[email protected]> contract SecuredTokenTransfer { /// @dev Transfers a token and returns if it was a success /// @param token Token that should be transferred /// @param receiver Receiver to whom the token should be transferred /// @param amount The amount of tokens that should be transferred function transferToken( address token, address receiver, uint256 amount ) internal returns (bool transferred) { // 0xa9059cbb - keccack("transfer(address,uint256)") bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount); // solhint-disable-next-line no-inline-assembly assembly { // We write the return value to scratch space. // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20) switch returndatasize() case 0 { transferred := success } case 0x20 { transferred := iszero(or(iszero(success), iszero(mload(0)))) } default { transferred := 0 } } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SelfAuthorized - authorizes current contract to perform actions /// @author Richard Meissner - <[email protected]> contract SelfAuthorized { function requireSelfCall() private view { require(msg.sender == address(this), "GS031"); } modifier authorized() { // This is a function call as it minimized the bytecode size requireSelfCall(); _; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SignatureDecoder - Decodes signatures that a encoded as bytes /// @author Richard Meissner - <[email protected]> contract SignatureDecoder { /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`. /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access /// @param signatures concatenated rsv signatures function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns ( uint8 v, bytes32 r, bytes32 s ) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. // solhint-disable-next-line no-inline-assembly assembly { let signaturePos := mul(0x41, pos) r := mload(add(signatures, add(signaturePos, 0x20))) s := mload(add(signatures, add(signaturePos, 0x40))) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Singleton - Base for singleton contracts (should always be first super contract) /// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`) /// @author Richard Meissner - <[email protected]> contract Singleton { // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract. // It should also always be ensured that the address is stored alone (uses a full word) address private singleton; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title StorageAccessible - generic base contract that allows callers to access all internal storage. /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol contract StorageAccessible { /** * @dev Reads `length` bytes of storage in the currents contract * @param offset - the offset in the current contract's storage in words to start reading from * @param length - the number of words (32 bytes) of data to read * @return the bytes that were read. */ function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) { bytes memory result = new bytes(length * 32); for (uint256 index = 0; index < length; index++) { // solhint-disable-next-line no-inline-assembly assembly { let word := sload(add(offset, index)) mstore(add(add(result, 0x20), mul(index, 0x20)), word) } } return result; } /** * @dev Performs a delegetecall on a targetContract in the context of self. * Internally reverts execution to avoid side effects (making it static). * * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`. * Specifically, the `returndata` after a call to this method will be: * `success:bool || response.length:uint256 || response:bytes`. * * @param targetContract Address of the contract containing the code to execute. * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments). */ function simulateAndRevert(address targetContract, bytes memory calldataPayload) external { // solhint-disable-next-line no-inline-assembly assembly { let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0) mstore(0x00, success) mstore(0x20, returndatasize()) returndatacopy(0x40, 0, returndatasize()) revert(0, add(returndatasize(), 0x40)) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /** * @title GnosisSafeMath * @dev Math operations with safety checks that revert on error * Renamed from SafeMath to GnosisSafeMath to avoid conflicts * TODO: remove once open zeppelin update to solc 0.5.0 */ library GnosisSafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; contract ISignatureValidatorConstants { // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b; } abstract contract ISignatureValidator is ISignatureValidatorConstants { /** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x20c13b0b when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4); } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title GnosisSafeStorage - Storage layout of the Safe contracts to be used in libraries /// @author Richard Meissner - <[email protected]> contract GnosisSafeStorage { // From /common/Singleton.sol address internal singleton; // From /common/ModuleManager.sol mapping(address => address) internal modules; // From /common/OwnerManager.sol mapping(address => address) internal owners; uint256 internal ownerCount; uint256 internal threshold; // From /GnosisSafe.sol uint256 internal nonce; bytes32 internal _deprecatedDomainSeparator; mapping(bytes32 => uint256) internal signedMessages; mapping(address => mapping(bytes32 => uint256)) internal approvedHashes; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "./GnosisSafeStorage.sol"; import "../GnosisSafe.sol"; /// @title SignMessageLib - Allows to set an entry in the signedMessages /// @author Richard Meissner - <[email protected]> contract SignMessageLib is GnosisSafeStorage { //keccak256( // "SafeMessage(bytes message)" //); bytes32 private constant SAFE_MSG_TYPEHASH = 0x60b3cbf8b4a223d68d641b3b6ddf9a298e7f33710cf3d3a9d1146b5a6150fbca; event SignMsg(bytes32 indexed msgHash); /// @dev Marks a message as signed, so that it can be used with EIP-1271 /// @notice Marks a message (`_data`) as signed. /// @param _data Arbitrary length data that should be marked as signed on the behalf of address(this) function signMessage(bytes calldata _data) external { bytes32 msgHash = getMessageHash(_data); signedMessages[msgHash] = 1; emit SignMsg(msgHash); } /// @dev Returns hash of a message that can be signed by owners. /// @param message Message that should be hashed /// @return Message hash. function getMessageHash(bytes memory message) public view returns (bytes32) { bytes32 safeMessageHash = keccak256(abi.encode(SAFE_MSG_TYPEHASH, keccak256(message))); return keccak256(abi.encodePacked(bytes1(0x19), bytes1(0x01), GnosisSafe(payable(address(this))).domainSeparator(), safeMessageHash)); } }
@title GnosisSafeStorage - Storage layout of the Safe contracts to be used in libraries @author Richard Meissner - <[email protected]> From /common/Singleton.sol From /common/ModuleManager.sol From /common/OwnerManager.sol From /GnosisSafe.sol
contract GnosisSafeStorage { address internal singleton; mapping(address => address) internal modules; mapping(address => address) internal owners; uint256 internal ownerCount; uint256 internal threshold; uint256 internal nonce; bytes32 internal _deprecatedDomainSeparator; mapping(bytes32 => uint256) internal signedMessages; mapping(address => mapping(bytes32 => uint256)) internal approvedHashes; } pragma solidity >=0.7.0 <0.9.0; }
12,170,450
[ 1, 43, 18050, 291, 9890, 3245, 300, 5235, 3511, 434, 326, 14060, 20092, 358, 506, 1399, 316, 14732, 225, 534, 1354, 1060, 7499, 1054, 1224, 300, 411, 63, 3652, 131, 259, 1117, 65, 34, 6338, 342, 6054, 19, 19571, 18, 18281, 6338, 342, 6054, 19, 3120, 1318, 18, 18281, 6338, 342, 6054, 19, 5541, 1318, 18, 18281, 6338, 342, 43, 18050, 291, 9890, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 611, 18050, 291, 9890, 3245, 288, 203, 565, 1758, 2713, 6396, 31, 203, 565, 2874, 12, 2867, 516, 1758, 13, 2713, 4381, 31, 203, 565, 2874, 12, 2867, 516, 1758, 13, 2713, 25937, 31, 203, 565, 2254, 5034, 2713, 3410, 1380, 31, 203, 565, 2254, 5034, 2713, 5573, 31, 203, 203, 565, 2254, 5034, 2713, 7448, 31, 203, 565, 1731, 1578, 2713, 389, 14089, 3748, 6581, 31, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 2713, 6726, 5058, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 3890, 1578, 516, 2254, 5034, 3719, 2713, 20412, 14455, 31, 203, 97, 203, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 411, 20, 18, 29, 18, 20, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x10eE298D8445e507D6245ff2418C6608804486Cc/sources/contracts/libraries/constants/Lib_PredeployAddresses.sol
* @title Lib_PredeployAddresses/
library Lib_PredeployAddresses { 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 NVM_ETH = payable(0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000); 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; pragma solidity ^0.8.9; }
1,894,271
[ 1, 5664, 67, 1386, 12411, 7148, 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, 12083, 10560, 67, 1386, 12411, 7148, 288, 203, 565, 1758, 2713, 5381, 511, 22, 67, 4296, 67, 48, 21, 67, 8723, 67, 10884, 654, 273, 374, 92, 9452, 12648, 12648, 12648, 12648, 9449, 31, 203, 565, 1758, 2713, 5381, 511, 21, 67, 8723, 67, 1090, 18556, 273, 374, 92, 9452, 12648, 12648, 12648, 12648, 2787, 1611, 31, 203, 565, 1758, 2713, 5381, 2030, 22971, 654, 67, 16861, 7085, 273, 374, 92, 9452, 12648, 12648, 12648, 12648, 2787, 3103, 31, 203, 565, 1758, 8843, 429, 2713, 5381, 423, 7397, 67, 1584, 44, 273, 8843, 429, 12, 20, 92, 11852, 758, 1871, 323, 986, 41, 1871, 22097, 1639, 69, 40, 1639, 1871, 758, 69, 40, 758, 1880, 2787, 1769, 203, 565, 1758, 2713, 5381, 511, 22, 67, 39, 1457, 1260, 67, 18192, 67, 958, 12130, 50, 3101, 273, 203, 3639, 374, 92, 9452, 12648, 12648, 12648, 12648, 2787, 8642, 31, 203, 565, 1758, 2713, 5381, 23983, 67, 15140, 67, 19402, 273, 374, 92, 9452, 12648, 12648, 12648, 12648, 2787, 6840, 31, 203, 565, 1758, 2713, 5381, 26910, 67, 41, 28202, 273, 374, 92, 9452, 12648, 12648, 12648, 12648, 2787, 5908, 31, 203, 565, 1758, 2713, 5381, 511, 22, 67, 882, 18264, 67, 7192, 734, 7113, 273, 374, 92, 9452, 12648, 12648, 12648, 12648, 2787, 2163, 31, 203, 565, 1758, 2713, 5381, 3174, 3500, 30445, 654, 67, 8090, 41, 67, 59, 1013, 15146, 273, 374, 92, 9452, 12648, 12648, 12648, 12648, 2787, 2499, 31, 203, 565, 1758, 2713, 5381, 511, 22, 67, 882, 18264, 67, 8412, 67, 2 ]
./full_match/1/0x3D19912F1f1750CA91d6a0E859E27d4Ccd8218B7/sources/contracts/burn.sol
pancake address pancakeRouter = 0x10ED43C718714eb63d5aA57B78B54704E256024E; address wBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c;uniswap
contract burn{ address payable recipient = payable(0x9b6f240AbD4bA6fE3fb897cF179ce5D8b8bCEb0f); address pancakeRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address wBNB = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; constructor(){ } function burnToken(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount) public payable { IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function burnToken(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount) public payable { IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function burnToken(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount) public payable { IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function burnToken(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount) public payable { IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function burnToken(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount) public payable { IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function buyAndBurn(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount, uint256 buyAmount) public payable { if(otherToken == wBNB && msg.value > 0) { require(msg.value > 0, "require buyAmount"); } IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory buy_paths = new address[](2); buy_paths[0] = otherToken; buy_paths[1] = burnToken; address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens(buyAmount,0,buy_paths,address(this),block.timestamp); if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function buyAndBurn(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount, uint256 buyAmount) public payable { if(otherToken == wBNB && msg.value > 0) { require(msg.value > 0, "require buyAmount"); } IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory buy_paths = new address[](2); buy_paths[0] = otherToken; buy_paths[1] = burnToken; address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens(buyAmount,0,buy_paths,address(this),block.timestamp); if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } IERC20(wBNB).deposit{value:msg.value}(); function buyAndBurn(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount, uint256 buyAmount) public payable { if(otherToken == wBNB && msg.value > 0) { require(msg.value > 0, "require buyAmount"); } IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory buy_paths = new address[](2); buy_paths[0] = otherToken; buy_paths[1] = burnToken; address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens(buyAmount,0,buy_paths,address(this),block.timestamp); if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function buyAndBurn(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount, uint256 buyAmount) public payable { if(otherToken == wBNB && msg.value > 0) { require(msg.value > 0, "require buyAmount"); } IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory buy_paths = new address[](2); buy_paths[0] = otherToken; buy_paths[1] = burnToken; address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens(buyAmount,0,buy_paths,address(this),block.timestamp); if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function buyAndBurn(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount, uint256 buyAmount) public payable { if(otherToken == wBNB && msg.value > 0) { require(msg.value > 0, "require buyAmount"); } IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory buy_paths = new address[](2); buy_paths[0] = otherToken; buy_paths[1] = burnToken; address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens(buyAmount,0,buy_paths,address(this),block.timestamp); if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function buyAndBurn(address burnToken, address otherToken, address pairAddress, uint burnType, uint256 burnAmount, uint256 buyAmount) public payable { if(otherToken == wBNB && msg.value > 0) { require(msg.value > 0, "require buyAmount"); } IERC20(burnToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); IERC20(otherToken).approve(pancakeRouter,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address[] memory buy_paths = new address[](2); buy_paths[0] = otherToken; buy_paths[1] = burnToken; address[] memory sell_paths = new address[](2); sell_paths[0] = burnToken; sell_paths[1] = otherToken; IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens(buyAmount,0,buy_paths,address(this),block.timestamp); if (burnType == 0) { IburnFunc(burnToken).burn(pairAddress, burnAmount); } else if (burnType == 1) { IburnFunc(burnToken)._burn(pairAddress, burnAmount); } else if (burnType == 2) { IburnFunc(burnToken).burnFrom(pairAddress, burnAmount); } else if (burnType == 3) { IburnFunc(burnToken)._burnFrom(pairAddress, burnAmount); } IUniswapV2Pair(pairAddress).sync(); IUniswapV2Router02(pancakeRouter).swapExactTokensForTokens( IERC20(burnToken).balanceOf(address(this)), 0, sell_paths, recipient, block.timestamp); IERC20(otherToken).transfer(recipient,IERC20(otherToken).balanceOf(address(this))); } function withdrawBalance() external{ recipient.transfer(address(this).balance); } function withdrawToken(address token) external{ IERC20(token).transfer(recipient,IERC20(token).balanceOf(address(this))); } }
9,649,805
[ 1, 7355, 23780, 282, 1758, 2800, 23780, 8259, 273, 374, 92, 2163, 2056, 8942, 39, 27, 2643, 27, 3461, 24008, 4449, 72, 25, 69, 37, 10321, 38, 8285, 38, 6564, 27, 3028, 41, 5034, 3103, 24, 41, 31, 282, 1758, 341, 15388, 38, 273, 374, 6114, 70, 24, 19728, 38, 29, 8876, 72, 5718, 38, 1611, 70, 40, 21, 71, 38, 69, 41, 15259, 22, 758, 6840, 72, 29, 31331, 13459, 5908, 25, 71, 31, 318, 291, 91, 438, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 18305, 95, 203, 565, 1758, 8843, 429, 8027, 273, 8843, 429, 12, 20, 92, 29, 70, 26, 74, 28784, 5895, 40, 24, 70, 37, 26, 74, 41, 23, 19192, 6675, 27, 71, 42, 28814, 311, 25, 40, 28, 70, 28, 70, 1441, 70, 20, 74, 1769, 203, 565, 1758, 2800, 23780, 8259, 273, 374, 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, 31, 203, 565, 1758, 341, 15388, 38, 273, 374, 14626, 3103, 7598, 37, 5520, 70, 3787, 23, 8090, 28, 40, 20, 37, 20, 73, 25, 39, 24, 42, 5324, 73, 1880, 29, 6840, 23, 39, 27, 4313, 39, 71, 22, 31, 203, 203, 565, 3885, 1435, 95, 203, 565, 289, 203, 203, 203, 565, 445, 18305, 1345, 12, 2867, 18305, 1345, 16, 1758, 1308, 1345, 16, 1758, 3082, 1887, 16, 225, 2254, 18305, 559, 16, 2254, 5034, 18305, 6275, 13, 1071, 8843, 429, 288, 203, 203, 3639, 467, 654, 39, 3462, 12, 70, 321, 1345, 2934, 12908, 537, 12, 7355, 23780, 8259, 16, 20, 5297, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 1769, 203, 3639, 467, 654, 39, 3462, 12, 3011, 1345, 2934, 12908, 537, 12, 7355, 23780, 8259, 16, 20, 5297, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 1769, 203, 203, 3639, 1758, 8526, 3778, 225, 357, 80, 67, 4481, 273, 2 ]
pragma solidity ^0.4.23; import "./EntryStorage.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Destructible } from "openzeppelin-solidity/contracts/lifecycle/Destructible.sol"; contract Organisation is Destructible { /** * The organization can be upgradeable. * In this contract you can upgrade functionality which uses separate storage. */ // It prevents overflow issues using SafeMath for uint256; // Address of external storage contract address public entryStorageAddr; // Emitted when new Entry addedd event EntryAdded(uint256 indexed entryId); // Emitted when exist a new submission event Submitted(uint256 indexed entryId); // Emitted when an Entry submission is accepted event SubmissionAccepted(uint256 indexed entryId); // Emitted when an Entry is cancelled event EntryCancelled(uint256 indexed entryId); // Emitted when bounty is claimed event BountyClaimed(uint256 indexed entryId); /** * @notice Sets the address of the EntryStorage contract * @param _entryStorageAddr address Address of storage contract */ function setDataStore(address _entryStorageAddr) public { entryStorageAddr = _entryStorageAddr; } /** * @notice Adds an entry on the entries persistent storage * @param _specDigest bytes32 IPFS digest of the entry specification * @param _specHashFunction uint8 IPFS hash function of the entry specification * @param _specSize uint8 IPFS size of the entry specification */ function addEntry(bytes32 _specDigest, uint8 _specHashFunction, uint8 _specSize) public payable returns (uint256) { EntryStorage entryStorage = EntryStorage(entryStorageAddr); uint256 entryCount = entryStorage.addEntry.value(msg.value)(msg.sender, _specDigest, _specHashFunction, _specSize); emit EntryAdded(entryCount); return entryCount; } /** * @notice Gets the entry from the EntryStorage contract * @param _entryId uint256 The entry ID * @return uint Entry id * @return address Entry owner * @return uint Entry bounty * @return bytes32 IPFS digest of the entry specification * @return uint8 IPFS hash function of the entry specification * @return uint8 IPFS size of the entry specification * @return uint Entry created timestamp * @return uint Entry number of submissions * @return uint Entry state * @return bool Is bounty has been collected */ function getEntry(uint256 _entryId) public view returns (uint, address, uint, bytes32, uint8, uint8, uint, uint, uint, bool) { EntryStorage entryStorage = EntryStorage(entryStorageAddr); return entryStorage.getEntry(_entryId); } /** * @notice Get entry count */ function getEntryCount() public view returns (uint256) { EntryStorage entryStorage = EntryStorage(entryStorageAddr); return entryStorage.getEntryCount(); } /** * @notice Cancel the entry * @param _entryId uint256 The entry ID */ function cancelEntry(uint256 _entryId) public { EntryStorage entryStorage = EntryStorage(entryStorageAddr); entryStorage.cancelEntry(_entryId, msg.sender); emit EntryCancelled(_entryId); } /** * @notice Submits to a new entry * @param _entryId uint256 The entry ID * @param _specDigest bytes32 IPFS digest of the submission specification * @param _specHashFunction uint8 IPFS hash function of the submission specification * @param _specSize uint8 IPFS size of the submission specification */ function submit( uint256 _entryId, bytes32 _specDigest, uint8 _specHashFunction, uint8 _specSize ) public { EntryStorage entryStorage = EntryStorage(entryStorageAddr); entryStorage.submit(_entryId, msg.sender, _specDigest, _specHashFunction, _specSize); emit Submitted(_entryId); } /** * @notice Gets the submission from the EntryStorage contract * @param _entryId uint256 The entry ID * @param _submissionId uint256 The submission ID * @return uint Submission id * @return address Submission owner * @return bytes32 IPFS digest of the submission specification * @return uint8 IPFS hash function of the submission specification * @return uint8 IPFS size of the submission specification * @return uint Submission created timestamp */ function getSubmission(uint256 _entryId, uint256 _submissionId) public view returns (uint, address, bytes32, uint8, uint8, uint) { EntryStorage entryStorage = EntryStorage(entryStorageAddr); return entryStorage.getSubmission(_entryId, _submissionId); } /** * @notice Accepts the submission * @param _entryId uint256 The entry ID * @param _submissionId uint256 The submission ID */ function acceptSubmission(uint256 _entryId, uint256 _submissionId) public { EntryStorage entryStorage = EntryStorage(entryStorageAddr); entryStorage.acceptSubmission(_entryId, _submissionId, msg.sender); emit SubmissionAccepted(_entryId); } /** * @notice Get entry accepted submission * @param _entryId uint256 The entry ID * @return uint Submission id * @return address Submission owner * @return bytes32 IPFS digest of the submission specification * @return uint8 IPFS hash function of the submission specification * @return uint8 IPFS size of the submission specification * @return uint Submission created timestamp */ function getAcceptedSubmission(uint256 _entryId) public view returns (uint, address, bytes32, uint8, uint8, uint) { EntryStorage entryStorage = EntryStorage(entryStorageAddr); return entryStorage.getAcceptedSubmission(_entryId); } /** * @notice Claims the bounty for a given @param _entryId * @param _entryId uint256 The entry ID */ function claimBounty(uint256 _entryId) public { EntryStorage entryStorage = EntryStorage(entryStorageAddr); entryStorage.claimBounty(_entryId, msg.sender); emit BountyClaimed(_entryId); } /** * @notice Kills this contract and sends remaining ETH to @param transferAddress_ * @param transferAddress_ address remaining ETH will be sent to */ function kill(address transferAddress_) public { destroyAndSend(transferAddress_); } }
* @notice Submits to a new entry @param _entryId uint256 The entry ID @param _specDigest bytes32 IPFS digest of the submission specification @param _specHashFunction uint8 IPFS hash function of the submission specification @param _specSize uint8 IPFS size of the submission specification/
function submit( uint256 _entryId, bytes32 _specDigest, uint8 _specHashFunction, uint8 _specSize ) public { EntryStorage entryStorage = EntryStorage(entryStorageAddr); entryStorage.submit(_entryId, msg.sender, _specDigest, _specHashFunction, _specSize); emit Submitted(_entryId); }
6,443,176
[ 1, 1676, 22679, 358, 279, 394, 1241, 225, 389, 4099, 548, 2254, 5034, 1021, 1241, 1599, 225, 389, 2793, 9568, 1731, 1578, 2971, 4931, 5403, 434, 326, 8515, 7490, 225, 389, 2793, 2310, 2083, 2254, 28, 2971, 4931, 1651, 445, 434, 326, 8515, 7490, 225, 389, 2793, 1225, 2254, 28, 2971, 4931, 963, 434, 326, 8515, 7490, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4879, 12, 203, 3639, 2254, 5034, 389, 4099, 548, 16, 203, 3639, 1731, 1578, 389, 2793, 9568, 16, 203, 3639, 2254, 28, 389, 2793, 2310, 2083, 16, 203, 3639, 2254, 28, 389, 2793, 1225, 203, 565, 262, 1071, 288, 203, 3639, 3841, 3245, 1241, 3245, 273, 3841, 3245, 12, 4099, 3245, 3178, 1769, 203, 3639, 1241, 3245, 18, 9297, 24899, 4099, 548, 16, 1234, 18, 15330, 16, 389, 2793, 9568, 16, 389, 2793, 2310, 2083, 16, 389, 2793, 1225, 1769, 203, 3639, 3626, 2592, 7948, 24899, 4099, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xF4A5457aD563FE423FC60D4Ff1F00c90c05fCDEb/sources/@layerzerolabs/solidity-examples/contracts/token/oft/v2/fee/OFTWithFee.sol
*********************************************************************** internal functions/
function _debitFrom(address _from, uint16, bytes32, uint _amount) internal virtual override returns (uint) { address spender = _msgSender(); if (_from != spender) _spendAllowance(_from, spender, _amount); _burn(_from, _amount); return _amount; }
1,852,412
[ 1, 7236, 4186, 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, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 323, 3682, 1265, 12, 2867, 389, 2080, 16, 2254, 2313, 16, 1731, 1578, 16, 2254, 389, 8949, 13, 2713, 5024, 3849, 1135, 261, 11890, 13, 288, 203, 3639, 1758, 17571, 264, 273, 389, 3576, 12021, 5621, 203, 3639, 309, 261, 67, 2080, 480, 17571, 264, 13, 389, 87, 1302, 7009, 1359, 24899, 2080, 16, 17571, 264, 16, 389, 8949, 1769, 203, 3639, 389, 70, 321, 24899, 2080, 16, 389, 8949, 1769, 203, 3639, 327, 389, 8949, 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 ]
pragma solidity 0.4.25; contract Nodes { address public owner; mapping (uint => Node) public nodes; mapping (string => uint) nodesID; mapping (string => uint16) nodeGroupsId; mapping (uint16 => string) public nodeGroups; mapping (address => string) public confirmationNodes; uint16 public nodeGroupID; uint public nodeID; struct Node { string nodeName; address producer; address node; uint256 date; uint8 starmidConfirmed; //0 - not confirmed; 1 - confirmed; 2 - caution string confirmationPost; outsourceConfirmStruct[] outsourceConfirmed; uint16[] nodeGroup; uint8 producersPercent; } struct outsourceConfirmStruct { uint8 confirmationStatus; address confirmationNode; string confirmationPost; } event NewNode( uint256 id, string nodeName, uint8 producersPercent, address producer, uint date ); event NewNodeGroup(uint16 id, string newNodeGroup); event AddNodeAddress(uint nodeID, address nodeAdress); event EditNode(uint nodeID, address newProducer, uint8 newProducersPercent); event ConfirmNode(uint nodeID, uint8 confirmationStatus, string confirmationPost); event OutsourceConfirmNode(uint nodeID, uint8 confirmationStatus, address confirmationNode, string confirmationPost); event ChangePercent(uint nodeId, uint producersPercent); event PushNodeGroup(uint nodeId, uint newNodeGroup); event DeleteNodeGroup(uint nodeId, uint deleteNodeGroup); modifier onlyOwner { require(msg.sender == owner); _; } function addConfirmationNode(string _newConfirmationNode) public returns(bool) { confirmationNodes[msg.sender] = _newConfirmationNode; return true; } function addNodeGroup(string _newNodeGroup) public onlyOwner returns(bool _result, uint16 _id) { require (nodeGroupsId[_newNodeGroup] == 0); _id = nodeGroupID += 1; nodeGroups[_id] = _newNodeGroup; nodeGroupsId[_newNodeGroup] = nodeGroupID; _result = true; emit NewNodeGroup(_id, _newNodeGroup); } function addNode(string _newNode, uint8 _producersPercent) public returns (bool _result, uint _id) { require(nodesID[_newNode] < 1 && _producersPercent < 100); _id = nodeID += 1; require(nodeID < 1000000000000); nodes[nodeID].nodeName = _newNode; nodes[nodeID].producer = msg.sender; nodes[nodeID].date = block.timestamp; nodes[nodeID].producersPercent = _producersPercent; nodesID[_newNode] = nodeID; emit NewNode(_id, _newNode, _producersPercent, msg.sender, block.timestamp); _result = true; } function editNode( uint _nodeID, address _newProducer, uint8 _newProducersPercent ) public onlyOwner returns (bool) { nodes[_nodeID].producer = _newProducer; nodes[_nodeID].producersPercent = _newProducersPercent; emit EditNode(_nodeID, _newProducer, _newProducersPercent); return true; } function addNodeAddress(uint _nodeID, address _nodeAddress) public returns(bool _result) { require(msg.sender == nodes[_nodeID].producer && nodes[_nodeID].node == 0); nodes[_nodeID].node = _nodeAddress; emit AddNodeAddress( _nodeID, _nodeAddress); _result = true; } function pushNodeGroup(uint _nodeID, uint16 _newNodeGroup) public returns(bool) { require(msg.sender == nodes[_nodeID].node || msg.sender == nodes[_nodeID].producer); nodes[_nodeID].nodeGroup.push(_newNodeGroup); emit PushNodeGroup(_nodeID, _newNodeGroup); return true; } function deleteNodeGroup(uint _nodeID, uint16 _deleteNodeGroup) public returns(bool) { require(msg.sender == nodes[_nodeID].node || msg.sender == nodes[_nodeID].producer); for(uint16 i = 0; i < nodes[_nodeID].nodeGroup.length; i++) { if(_deleteNodeGroup == nodes[_nodeID].nodeGroup[i]) { for(uint16 ii = i; ii < nodes[_nodeID].nodeGroup.length - 1; ii++) nodes[_nodeID].nodeGroup[ii] = nodes[_nodeID].nodeGroup[ii + 1]; delete nodes[_nodeID].nodeGroup[nodes[_nodeID].nodeGroup.length - 1]; nodes[_nodeID].nodeGroup.length--; break; } } emit DeleteNodeGroup(_nodeID, _deleteNodeGroup); return true; } function confirmNode(uint _nodeID, string confirmationPost, uint8 confirmationStatus) public onlyOwner returns(bool) { nodes[_nodeID].starmidConfirmed = confirmationStatus; nodes[_nodeID].confirmationPost = confirmationPost; emit ConfirmNode(_nodeID, confirmationStatus, confirmationPost); return true; } function outsourceConfirmNode(uint _nodeID, string confirmationPost, uint8 confirmationStatus) public returns(bool) { nodes[_nodeID].outsourceConfirmed.push(outsourceConfirmStruct(confirmationStatus, msg.sender, confirmationPost)); emit OutsourceConfirmNode(_nodeID, confirmationStatus, msg.sender, confirmationPost); return true; } function changePercent(uint _nodeId, uint8 _producersPercent) public returns(bool) { require(msg.sender == nodes[_nodeId].producer && nodes[_nodeId].node == 0x0000000000000000000000000000000000000000); nodes[_nodeId].producersPercent = _producersPercent; emit ChangePercent(_nodeId, _producersPercent); return true; } function getNodeInfo(uint _nodeID) constant public returns( address _producer, address _node, uint _date, uint8 _starmidConfirmed, string _nodeName, uint16[] _nodeGroup, uint _producersPercent, string _confirmationPost ) { _producer = nodes[_nodeID].producer; _node = nodes[_nodeID].node; _date = nodes[_nodeID].date; _starmidConfirmed = nodes[_nodeID].starmidConfirmed; _nodeName = nodes[_nodeID].nodeName; _nodeGroup = nodes[_nodeID].nodeGroup; _producersPercent = nodes[_nodeID].producersPercent; _confirmationPost = nodes[_nodeID].confirmationPost; } function getOutsourceConfirmation(uint _nodeID, uint _number) constant public returns( uint _confirmationStatus, address _confirmationNode, string _confirmationNodeName, string _confirmationPost ) { _confirmationStatus = nodes[_nodeID].outsourceConfirmed[_number].confirmationStatus; _confirmationNode = nodes[_nodeID].outsourceConfirmed[_number].confirmationNode; _confirmationNodeName = confirmationNodes[_confirmationNode]; _confirmationPost = nodes[_nodeID].outsourceConfirmed[_number].confirmationPost; } } contract Starmid is Nodes { uint24 public emissionLimits; uint8 public feeMultipliedByTen; mapping (uint => emissionNodeInfo) public emissions; mapping (address => mapping (uint => uint)) balanceOf; mapping (address => mapping (uint => uint)) frozen; uint128 public orderId; mapping (uint => mapping (uint => orderInfo[])) buyOrders; mapping (uint => mapping (uint => orderInfo[])) sellOrders; mapping (uint => uint[]) buyOrderPrices; mapping (uint => uint[]) sellOrderPrices; mapping (address => uint) public pendingWithdrawals; address public multiKey; struct orderInfo { address client; uint amount; uint orderId; uint8 fee; } struct emissionNodeInfo { uint emissionNumber; uint date; } event Emission(uint node, uint date); event BuyOrder(uint orderId, uint node, uint buyPrice, uint amount); event SellOrder(uint orderId, uint node, uint sellPrice, uint amount); event CancelBuyOrder(uint orderId, uint node, uint price); event CancelSellOrder(uint orderId, uint node, uint price); event TradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId); constructor() public { owner = msg.sender; emissionLimits = 1000000; feeMultipliedByTen = 20; } //-----------------------------------------------------Starmid Exchange------------------------------------------------------ function withdraw() public returns(bool _result, uint _amount) { _amount = pendingWithdrawals[msg.sender]; pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(_amount); _result = true; } function changeOwner(address _newOwnerAddress) public returns(bool) { require(msg.sender == owner || msg.sender == 0x1335995a62a6769b0a44a8fcc08d9c3324456df0); if(multiKey == 0x0000000000000000000000000000000000000000) multiKey = msg.sender; if(multiKey == owner && msg.sender == 0x1335995a62a6769b0a44a8fcc08d9c3324456df0) { owner = _newOwnerAddress; multiKey = 0x0000000000000000000000000000000000000000; return true; } if(multiKey == 0x1335995a62a6769b0a44a8fcc08d9c3324456df0 && msg.sender == owner) { owner = _newOwnerAddress; multiKey = 0x0000000000000000000000000000000000000000; return true; } } function changeFee(uint8 _newFee) public onlyOwner returns(bool) { feeMultipliedByTen = _newFee; return true; } function getEmission(uint _node) constant public returns(uint _emissionNumber, uint _emissionDate) { _emissionNumber = emissions[_node].emissionNumber; _emissionDate = emissions[_node].date; } function emission(uint _node) public returns(bool _result, uint _producersPercent) { address _nodeProducer = nodes[_node].producer; address _nodeOwner = nodes[_node].node; _producersPercent = nodes[_node].producersPercent; require(msg.sender == _nodeOwner || msg.sender == _nodeProducer); require(_nodeOwner != 0x0000000000000000000000000000000000000000 && emissions[_node].emissionNumber == 0); balanceOf[_nodeOwner][_node] += emissionLimits*(100 - _producersPercent)/100; balanceOf[_nodeProducer][_node] += emissionLimits*_producersPercent/100; emissions[_node].date = block.timestamp; emissions[_node].emissionNumber = 1; emit Emission(_node, block.timestamp); _result = true; } function getStockBalance(address _address, uint _node) constant public returns(uint _balance) { _balance = balanceOf[_address][_node]; } function getWithFrozenStockBalance(address _address, uint _node) constant public returns(uint _balance) { _balance = balanceOf[_address][_node] + frozen[_address][_node]; } function getOrderInfo(bool _isBuyOrder, uint _node, uint _price, uint _number) constant public returns (address _address, uint _amount, uint _orderId, uint8 _fee) { if(_isBuyOrder == true) { _address = buyOrders[_node][_price][_number].client; _amount = buyOrders[_node][_price][_number].amount; _orderId = buyOrders[_node][_price][_number].orderId; _fee = buyOrders[_node][_price][_number].fee; } else { _address = sellOrders[_node][_price][_number].client; _amount = sellOrders[_node][_price][_number].amount; _orderId = sellOrders[_node][_price][_number].orderId; } } function getBuyOrderPrices(uint _node) constant public returns(uint[] _prices) { _prices = buyOrderPrices[_node]; } function getSellOrderPrices(uint _node) constant public returns(uint[] _prices) { _prices = sellOrderPrices[_node]; } function buyOrder(uint _node, uint _buyPrice, uint _amount) payable public returns (bool _result, uint _orderId) { //check if there is a better price uint _minSellPrice = _buyPrice + 1; for (uint i = 0; i < sellOrderPrices[_node].length; i++) { if(sellOrderPrices[_node][i] < _minSellPrice) _minSellPrice = sellOrderPrices[_node][i]; } require(_node > 0 && _buyPrice > 0 && _amount > 0 && msg.value > 0 && _buyPrice < _minSellPrice); require(msg.value == _amount*_buyPrice + _amount*_buyPrice*feeMultipliedByTen/1000); _orderId = orderId += 1; buyOrders[_node][_buyPrice].push(orderInfo(msg.sender, _amount, _orderId, feeMultipliedByTen)); //Add _buyPrice to buyOrderPrices[_node][] uint it = 999999; for (uint itt = 0; itt < buyOrderPrices[_node].length; itt++) { if (buyOrderPrices[_node][itt] == _buyPrice) it = itt; } if (it == 999999) buyOrderPrices[_node].push(_buyPrice); _result = true; emit BuyOrder(orderId, _node, _buyPrice, _amount); } function sellOrder(uint _node, uint _sellPrice, uint _amount) public returns (bool _result, uint _orderId) { //check if there is a better price uint _maxBuyPrice = _sellPrice - 1; for (uint i = 0; i < buyOrderPrices[_node].length; i++) { if(buyOrderPrices[_node][i] > _maxBuyPrice) _maxBuyPrice = buyOrderPrices[_node][i]; } require(_node > 0 && _sellPrice > 0 && _amount > 0 && balanceOf[msg.sender][_node] >= _amount && _sellPrice > _maxBuyPrice); _orderId = orderId += 1; sellOrders[_node][_sellPrice].push(orderInfo(msg.sender, _amount, _orderId, feeMultipliedByTen)); //transfer stocks to the frozen balance frozen[msg.sender][_node] += _amount; balanceOf[msg.sender][_node] -= _amount; //Add _sellPrice to sellOrderPrices[_node][] uint it = 999999; for (uint itt = 0; itt < sellOrderPrices[_node].length; itt++) { if (sellOrderPrices[_node][itt] == _sellPrice) it = itt; } if (it == 999999) sellOrderPrices[_node].push(_sellPrice); _result = true; emit SellOrder(orderId, _node, _sellPrice, _amount); } function cancelBuyOrder(uint _node, uint _orderId, uint _price) public returns (bool _result) { orderInfo[] buyArr = buyOrders[_node][_price]; for (uint iii = 0; iii < buyArr.length; iii++) { if (buyArr[iii].orderId == _orderId) { require(msg.sender == buyArr[iii].client); pendingWithdrawals[msg.sender] += _price*buyArr[iii].amount + _price*buyArr[iii].amount*buyArr[iii].fee/1000;//returns ether and fee to the buyer //delete buyOrders[_node][_price][iii] and move each element for (uint ii = iii; ii < buyArr.length - 1; ii++) { buyArr[ii] = buyArr[ii + 1]; } delete buyArr[buyArr.length - 1]; buyArr.length--; break; } } //Delete _price from buyOrderPrices[_node][] if it's the last order if (buyArr.length == 0) { uint _fromArg = 99999; for (iii = 0; iii < buyOrderPrices[_node].length - 1; iii++) { if (buyOrderPrices[_node][iii] == _price) { _fromArg = iii; } if (_fromArg != 99999 && iii >= _fromArg) buyOrderPrices[_node][iii] = buyOrderPrices[_node][iii + 1]; } delete buyOrderPrices[_node][buyOrderPrices[_node].length-1]; buyOrderPrices[_node].length--; } _result = true; emit CancelBuyOrder(_orderId, _node, _price); } function cancelSellOrder(uint _node, uint _orderId, uint _price) public returns (bool _result) { orderInfo[] sellArr = sellOrders[_node][_price]; for (uint iii = 0; iii < sellArr.length; iii++) { if (sellArr[iii].orderId == _orderId) { require(msg.sender == sellArr[iii].client); //return stocks from the frozen balance to seller frozen[msg.sender][_node] -= sellArr[iii].amount; balanceOf[msg.sender][_node] += sellArr[iii].amount; //delete sellOrders[_node][_price][iii] and move each element for (uint ii = iii; ii < sellArr.length - 1; ii++) { sellArr[ii] = sellArr[ii + 1]; } delete sellArr[sellArr.length - 1]; sellArr.length--; break; } } //Delete _price from sellOrderPrices[_node][] if it's the last order if (sellArr.length == 0) { uint _fromArg = 99999; for (iii = 0; iii < sellOrderPrices[_node].length - 1; iii++) { if (sellOrderPrices[_node][iii] == _price) { _fromArg = iii; } if (_fromArg != 99999 && iii >= _fromArg) sellOrderPrices[_node][iii] = sellOrderPrices[_node][iii + 1]; } delete sellOrderPrices[_node][sellOrderPrices[_node].length-1]; sellOrderPrices[_node].length--; } _result = true; emit CancelSellOrder(_orderId, _node, _price); } function buyCertainOrder(uint _node, uint _price, uint _amount, uint _orderId) payable public returns (bool _result) { require(_node > 0 && _price > 0 && _amount > 0 && msg.value > 0 ); orderInfo[] sellArr = sellOrders[_node][_price]; for (uint iii = 0; iii < sellArr.length; iii++) { if (sellArr[iii].orderId == _orderId) { require(_amount <= sellArr[iii].amount && msg.value == _amount*_price + _amount*_price*feeMultipliedByTen/1000); address _client = sellArr[iii].client; //buy stocks for ether balanceOf[msg.sender][_node] += _amount;// adds the amount to buyer's balance frozen[_client][_node] -= _amount;// subtracts the amount from seller's frozen balance //transfer ether to the seller and fee to a contract owner pendingWithdrawals[_client] += _price*_amount; pendingWithdrawals[owner] += _price*_amount*feeMultipliedByTen/1000; //save the transaction emit TradeHistory(_node, block.timestamp, msg.sender, _client, _price, _amount, _orderId); //delete sellArr[iii] and move each element if (_amount == sellArr[iii].amount) { for (uint ii = iii; ii < sellArr.length - 1; ii++) sellArr[ii] = sellArr[ii + 1]; delete sellArr[sellArr.length - 1]; sellArr.length--; } else { sellArr[iii].amount = sellArr[iii].amount - _amount;//edit sellOrders } //Delete _price from sellOrderPrices[_node][] if it's the last order if (sellArr.length == 0) { uint _fromArg = 99999; for (uint i = 0; i < sellOrderPrices[_node].length - 1; i++) { if (sellOrderPrices[_node][i] == _price) { _fromArg = i; } if (_fromArg != 99999 && i >= _fromArg) sellOrderPrices[_node][i] = sellOrderPrices[_node][i + 1]; } delete sellOrderPrices[_node][sellOrderPrices[_node].length-1]; sellOrderPrices[_node].length--; } break; } } _result = true; } function sellCertainOrder(uint _node, uint _price, uint _amount, uint _orderId) public returns (bool _result) { require(_node > 0 && _price > 0 && _amount > 0 ); orderInfo[] buyArr = buyOrders[_node][_price]; for (uint iii = 0; iii < buyArr.length; iii++) { if (buyArr[iii].orderId == _orderId) { require(_amount <= buyArr[iii].amount && balanceOf[msg.sender][_node] >= _amount); address _client = buyArr[iii].client; //sell stocks for ether balanceOf[_client][_node] += _amount;// adds the amount to buyer's balance balanceOf[msg.sender][_node] -= _amount;// subtracts the amount from seller's frozen balance //transfer ether to the seller and fee to a contract owner pendingWithdrawals[msg.sender] += _price*_amount; pendingWithdrawals[owner] += _price*_amount*buyArr[iii].fee/1000; //save the transaction emit TradeHistory(_node, block.timestamp, _client, msg.sender, _price, _amount, _orderId); //delete buyArr[iii] and move each element if (_amount == buyArr[iii].amount) { for (uint ii = iii; ii < buyArr.length - 1; ii++) buyArr[ii] = buyArr[ii + 1]; delete buyArr[buyArr.length - 1]; buyArr.length--; } else { buyArr[iii].amount = buyArr[iii].amount - _amount;//edit buyOrders } //Delete _price from buyOrderPrices[_node][] if it's the last order if (buyArr.length == 0) { uint _fromArg = 99999; for (uint i = 0; i < buyOrderPrices[_node].length - 1; i++) { if (buyOrderPrices[_node][i] == _price) { _fromArg = i; } if (_fromArg != 99999 && i >= _fromArg) buyOrderPrices[_node][i] = buyOrderPrices[_node][i + 1]; } delete buyOrderPrices[_node][buyOrderPrices[_node].length-1]; buyOrderPrices[_node].length--; } break; } } _result = true; } }
subtracts the amount from seller's frozen balance
balanceOf[msg.sender][_node] -= _amount;
945,274
[ 1, 1717, 1575, 87, 326, 3844, 628, 29804, 1807, 12810, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9506, 202, 12296, 951, 63, 3576, 18, 15330, 6362, 67, 2159, 65, 3947, 389, 8949, 31, 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 ]
./full_match/56/0x1B709b583ff354e35910020a6E540984b4fa174e/sources/contracts/latests/StratX.sol
import "https:github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol";
library Address { function _beforeTokenTransfer( address from, address to, uint256 amount } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function _beforeTokenTransfer( address from, address to, uint256 amount } 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"); (bool success, bytes memory returndata) = return _verifyCallResult(success, returndata, errorMessage); } 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 ) private 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 ) private 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 ) private 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 ) private 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 { }
3,228,776
[ 1, 5666, 315, 4528, 30, 6662, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 19, 10721, 19, 7525, 19, 16351, 87, 19, 2316, 19, 654, 39, 3462, 19, 9890, 654, 39, 3462, 18, 18281, 14432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 5267, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 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, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 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, 203, 5411, 1758, 12, 2211, 2934, 12296, 1545, 3844, 16, 203, 5411, 315, 1887, 30, 2763, 11339, 11013, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 2216, 16, 203, 5411, 315, 1887, 30, 13496, 358, 1366, 460, 16, 8027, 2026, 1240, 15226, 329, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 3639, 261, 6430, 2216, 16, 262, 273, 8027, 18, 1991, 95, 1132, 30, 3844, 97, 2932, 8863, 203, 565, 445, 445, 2 ]
./full_match/1/0x016C8f5BA33475570cDD6c3948A1D3E06fF4cd20/sources/contracts/ZappedPaymentSplitter.sol
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an IERC20 contract./
function released( IERC20 token, address account ) public view returns (uint256) { return _erc20Released[token][account]; }
2,913,591
[ 1, 8461, 364, 326, 3844, 434, 1375, 2316, 68, 2430, 1818, 15976, 358, 279, 8843, 1340, 18, 1375, 2316, 68, 1410, 506, 326, 1758, 434, 392, 467, 654, 39, 3462, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 15976, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 1758, 2236, 203, 565, 262, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 12610, 3462, 26363, 63, 2316, 6362, 4631, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x31184eFEF1ccD72696FAcD35594af3aF2A537a3f/sources/ZCoreToken.sol
* @dev Burns a specific amount of tokens. @param _value The amount of token to be burned./ no need to require value <= totalSupply, since that would imply the sender's balance is greater than the totalSupply, which *should* be an assertion failure_value = _value / 100000000;
function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); _totalSupply = _totalSupply.sub(_value); Burn(burner, _value); }
11,068,740
[ 1, 38, 321, 87, 279, 2923, 3844, 434, 2430, 18, 225, 389, 1132, 1021, 3844, 434, 1147, 358, 506, 18305, 329, 18, 19, 1158, 1608, 358, 2583, 460, 1648, 2078, 3088, 1283, 16, 3241, 716, 4102, 709, 1283, 326, 5793, 1807, 11013, 353, 6802, 2353, 326, 2078, 3088, 1283, 16, 1492, 1410, 506, 392, 11240, 5166, 67, 1132, 273, 389, 1132, 342, 2130, 9449, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 288, 203, 3639, 2583, 24899, 1132, 405, 374, 1769, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 3576, 18, 15330, 19226, 203, 540, 203, 203, 3639, 1758, 18305, 264, 273, 1234, 18, 15330, 31, 203, 3639, 324, 26488, 63, 70, 321, 264, 65, 273, 324, 26488, 63, 70, 321, 264, 8009, 1717, 24899, 1132, 1769, 203, 3639, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 24899, 1132, 1769, 203, 3639, 605, 321, 12, 70, 321, 264, 16, 389, 1132, 1769, 203, 565, 289, 540, 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 ]
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "../utils/OperatorParams.sol"; import "../utils/BytesLib.sol"; /// Staking contract stub for testing purposes of copy stake flow. contract OldTokenStaking { using OperatorParams for uint256; using BytesLib for bytes; ERC20Burnable public token; using SafeERC20 for ERC20Burnable; event Undelegated(address indexed operator, uint256 undelegatedAt); event Staked(address indexed from, uint256 value); mapping(address => address[]) public ownerOperators; mapping(address => Operator) public operators; struct Operator { uint256 packedParams; address owner; address payable beneficiary; address authorizer; } constructor( address _tokenAddress ) public { require(_tokenAddress != address(0x0), "Token address can't be zero."); token = ERC20Burnable(_tokenAddress); } function operatorsOf(address _address) public view returns (address[] memory) { return ownerOperators[_address]; } function balanceOf(address _address) public view returns (uint256 balance) { return operators[_address].packedParams.getAmount(); } function ownerOf(address _operator) public view returns (address) { return operators[_operator].owner; } function beneficiaryOf(address _operator) public view returns (address payable) { return operators[_operator].beneficiary; } function authorizerOf(address _operator) public view returns (address) { return operators[_operator].authorizer; } function getDelegationInfo(address _operator) public view returns (uint256 amount, uint256 createdAt, uint256 undelegatedAt) { return operators[_operator].packedParams.unpack(); } function undelegationPeriod() public view returns(uint256) { return 5184000; // two months } function initializationPeriod() public view returns(uint256) { return 120; } function minimumStake() public view returns (uint256) { return 10000 * 1e18; } function undelegate(address _operator) public { uint256 oldParams = operators[_operator].packedParams; operators[_operator].packedParams = oldParams.setUndelegationTimestamp( block.timestamp ); emit Undelegated(_operator, block.timestamp); } function setOperator( address _owner, address _operator, address payable _beneficiary, address _authorizer, uint256 _value ) public { operators[_operator] = Operator( OperatorParams.pack(_value, block.timestamp, 0), _owner, _beneficiary, _authorizer ); ownerOperators[_owner].push(_operator); } function receiveApproval(address _from, uint256 _value, address _token, bytes memory _extraData) public { require(ERC20Burnable(_token) == token, "Token contract must be the same one linked to this contract."); require(_value >= minimumStake(), "Tokens amount must be greater than the minimum stake"); require(_extraData.length == 60, "Stake delegation data must be provided."); address payable beneficiary = address(uint160(_extraData.toAddress(0))); address operator = _extraData.toAddress(20); require(operators[operator].owner == address(0), "Operator address is already in use."); address authorizer = _extraData.toAddress(40); // Transfer tokens to this contract. token.safeTransferFrom(_from, address(this), _value); operators[operator] = Operator( OperatorParams.pack(_value, block.timestamp, 0), _from, beneficiary, authorizer ); ownerOperators[_from].push(operator); emit Staked(operator, _value); } }
Transfer tokens to this contract.
function receiveApproval(address _from, uint256 _value, address _token, bytes memory _extraData) public { require(ERC20Burnable(_token) == token, "Token contract must be the same one linked to this contract."); require(_value >= minimumStake(), "Tokens amount must be greater than the minimum stake"); require(_extraData.length == 60, "Stake delegation data must be provided."); address payable beneficiary = address(uint160(_extraData.toAddress(0))); address operator = _extraData.toAddress(20); require(operators[operator].owner == address(0), "Operator address is already in use."); address authorizer = _extraData.toAddress(40); token.safeTransferFrom(_from, address(this), _value); operators[operator] = Operator( OperatorParams.pack(_value, block.timestamp, 0), _from, beneficiary, authorizer ); ownerOperators[_from].push(operator); emit Staked(operator, _value); }
2,573,442
[ 1, 5912, 2430, 358, 333, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6798, 23461, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 2316, 16, 1731, 3778, 389, 7763, 751, 13, 1071, 288, 203, 3639, 2583, 12, 654, 39, 3462, 38, 321, 429, 24899, 2316, 13, 422, 1147, 16, 315, 1345, 6835, 1297, 506, 326, 1967, 1245, 8459, 358, 333, 6835, 1199, 1769, 203, 3639, 2583, 24899, 1132, 1545, 5224, 510, 911, 9334, 315, 5157, 3844, 1297, 506, 6802, 2353, 326, 5224, 384, 911, 8863, 203, 3639, 2583, 24899, 7763, 751, 18, 2469, 422, 4752, 16, 315, 510, 911, 23595, 501, 1297, 506, 2112, 1199, 1769, 203, 203, 3639, 1758, 8843, 429, 27641, 74, 14463, 814, 273, 1758, 12, 11890, 16874, 24899, 7763, 751, 18, 869, 1887, 12, 20, 3719, 1769, 203, 3639, 1758, 3726, 273, 389, 7763, 751, 18, 869, 1887, 12, 3462, 1769, 203, 3639, 2583, 12, 30659, 63, 9497, 8009, 8443, 422, 1758, 12, 20, 3631, 315, 5592, 1758, 353, 1818, 316, 999, 1199, 1769, 203, 3639, 1758, 16761, 273, 389, 7763, 751, 18, 869, 1887, 12, 7132, 1769, 203, 203, 3639, 1147, 18, 4626, 5912, 1265, 24899, 2080, 16, 1758, 12, 2211, 3631, 389, 1132, 1769, 203, 203, 3639, 12213, 63, 9497, 65, 273, 11097, 12, 203, 5411, 11097, 1370, 18, 2920, 24899, 1132, 16, 1203, 18, 5508, 16, 374, 3631, 203, 5411, 389, 2080, 16, 203, 5411, 27641, 74, 14463, 814, 16, 203, 5411, 16761, 203, 3639, 11272, 203, 3639, 3410, 24473, 63, 67, 2080, 8009, 6206, 12, 9497, 1769, 203, 203, 3639, 3626, 934, 9477, 2 ]
./partial_match/1/0x5A9D49679319FCF3AcFe5559602Dbf31A221BaD6/sources/Strategy.sol
* @notice Used to track which version of `StrategyAPI` this Strategy implements. @dev The Strategy's version must match the Vault's `API_VERSION`. @return A string which holds the current API version of this contract./
function apiVersion() public pure returns (string memory) { return "0.2.2"; }
4,014,272
[ 1, 6668, 358, 3298, 1492, 1177, 434, 1375, 4525, 2557, 68, 333, 19736, 225, 4792, 18, 225, 1021, 19736, 1807, 1177, 1297, 845, 326, 17329, 1807, 1375, 2557, 67, 5757, 8338, 327, 432, 533, 1492, 14798, 326, 783, 1491, 1177, 434, 333, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12051, 1435, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 315, 20, 18, 22, 18, 22, 14432, 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 ]
pragma solidity 0.5.13; import "./interfaces/IERC721Full.sol"; import "./utils/SafeMath.sol"; /// @title Augur Markets interface /// @notice Gets the winner of each market from Augur interface IMarket { function getWinningPayoutNumerator(uint256 _outcome) external view returns (uint256); } /// @title Dai contract interface /// @notice Various cash functions interface Cash { function approve(address _spender, uint256 _amount) external returns (bool); function balanceOf(address _ownesr) external view returns (uint256); function faucet(uint256 _amount) external; function transfer(address _to, uint256 _amount) external returns (bool); function transferFrom(address _from, address _to, uint256 _amount) external returns (bool); } /// @title Augur OICash interface /// @notice adding or removing open interest to secure the Augur Oracle interface OICash { function deposit(uint256 _amount) external returns (bool); function withdraw(uint256 _amount) external returns (bool); } //TODO: replace completesets with OICash //TODO: update design pattens to take into account the recent changes //TODO: change front end to only approve the same amount that is being sent //TODO: add test where someone calls exit and they are not the current owner //TODO: add tests where current owner calls newRental twice // ^ will also need to figure out how to pass this number in the correct format because decimal // ^ does not seem to work for more than 100 dai, it needs big number /// @title Harber /// @author Andrew Stanger contract Harber { using SafeMath for uint256; /// NUMBER OF TOKENS /// @dev also equals number of markets on augur uint256 constant public numberOfTokens = 20; /// CONTRACT VARIABLES /// ERC721: IERC721Full public team; /// Augur contracts: IMarket[numberOfTokens] public market; OICash public augur; Cash public cash; /// UINTS, ADDRESSES, BOOLS /// @dev my whiskey fund, for my 1% cut address private andrewsAddress; /// @dev the addresses of the various Augur binary markets. One market for each token. Initiated in the constructor and does not change. address[numberOfTokens] public marketAddresses; /// @dev in attodai (so $100 = 100000000000000000000) uint256[numberOfTokens] public price; /// @dev an easy way to track the above across all tokens. It should always increment at the same time as the above increments. uint256 public totalCollected; /// @dev used to determine the rent due. Rent is due for the period (now - timeLastCollected), at which point timeLastCollected is set to now. uint256[numberOfTokens] public timeLastCollected; /// @dev when a token was bought. used only for front end 'owned since' section. Rent collection only needs timeLastCollected. uint256[numberOfTokens] public timeAcquired; /// @dev tracks the position of the current owner in the ownerTracker mapping uint256[numberOfTokens] public currentOwnerIndex; /// WINNING OUTCOME VARIABLES /// @dev start with invalid winning outcome uint256 public winningOutcome = 42069; //// @dev so the function to manually set the winner can only be called long after /// @dev ...it should have resolved via Augur. Must be public so others can verify it is accurate. uint256 public marketExpectedResolutionTime; /// MARKET RESOLUTION VARIABLES /// @dev step1: bool public marketsResolved = false; // must be false for step1, true for step2 bool public marketsResolvedWithoutErrors = false; // set in step 1. If true, normal payout. If false, return all funds /// @dev step 2: bool public step2Complete = false; // must be false for step2, true for complete /// @dev step 3: bool public step3Complete = false; // must be false for step2, true for complete /// @dev complete: uint256 public daiAvailableToDistribute; /// STRUCTS struct purchase { address owner; uint256 price; } /// MAPPINGS /// @dev keeps track of all previous owners of a token, including the price, so that if the current owner's deposit runs out, /// @dev ...ownership can be reverted to a previous owner with the previous price. Index 0 is NOT used, this tells the contract to foreclose. /// @dev this does NOT keep a reliable list of all owners, if it reverts to a previous owner then the next owner will overwrite the owner that was in that slot. /// @dev the variable currentOwnerIndex is used to track the location of the current owner. mapping (uint256 => mapping (uint256 => purchase) ) public ownerTracker; /// @dev how many seconds each user has held each token for, for determining winnings mapping (uint256 => mapping (address => uint256) ) public timeHeld; /// @dev sums all the timeHelds for each token. Not required, but saves on gas when paying out. Should always increment at the same time as timeHeld mapping (uint256 => uint256) public totalTimeHeld; /// @dev keeps track of all the deposits for each token, for each owner. Unused deposits are not returned automatically when there is a new buyer. /// @dev they can be withdrawn manually however. Unused deposits are returned automatically upon resolution of the market mapping (uint256 => mapping (address => uint256) ) public deposits; /// @dev keeps track of all the rent paid by each user. So that it can be returned in case of an invalid market outcome. Only required in this instance. mapping (address => uint256) public collectedPerUser; ////////////// CONSTRUCTOR ////////////// constructor(address _andrewsAddress, address _addressOfToken, address _addressOfCashContract, address[numberOfTokens] memory _addressesOfMarkets, address _addressOfOICashContract, address _addressOfMainAugurContract, uint _marketExpectedResolutionTime) public { marketExpectedResolutionTime = _marketExpectedResolutionTime; andrewsAddress = _andrewsAddress; marketAddresses = _addressesOfMarkets; // this is to make the market addresses public so users can check the actual augur markets for themselves // external contract variables: team = IERC721Full(_addressOfToken); cash = Cash(_addressOfCashContract); augur = OICash(_addressOfOICashContract); // initialise arrays for (uint i = 0; i < numberOfTokens; i++) { currentOwnerIndex[i]=0; market[i] = IMarket(_addressesOfMarkets[i]); } // approve Augur contract to transfer this contract's dai cash.approve(_addressOfMainAugurContract,(2**256)-1); } event LogNewRental(address indexed newOwner, uint256 indexed newPrice, uint256 indexed tokenId); event LogPriceChange(uint256 indexed newPrice, uint256 indexed tokenId); event LogForeclosure(address indexed prevOwner, uint256 indexed tokenId); event LogRentCollection(uint256 indexed rentCollected, uint256 indexed tokenId); event LogReturnToPreviousOwner(uint256 indexed tokenId, address indexed previousOwner); event LogDepositWithdrawal(uint256 indexed daiWithdrawn, uint256 indexed tokenId, address indexed returnedTo); event LogDepositIncreased(uint256 indexed daiDeposited, uint256 indexed tokenId, address indexed sentBy); event LogExit(uint256 indexed tokenId); event LogStep1Complete(bool indexed didAugurMarketsResolve, uint256 indexed winningOutcome, bool indexed didAugurMarketsResolveCorrectly); event LogStep2Complete(uint256 indexed daiAvailableToDistribute); event LogWinningsPaid(address indexed paidTo, uint256 indexed amountPaid); event LogRentReturned(address indexed returnedTo, uint256 indexed amountReturned); event LogAndrewPaid(uint256 indexed additionsToWhiskeyFund); ////////////// MODIFIERS ////////////// /// @notice prevents functions from being interacted with after the end of the competition /// @dev should be on all public/external 'ordinary course of business' functions modifier notResolved() { require(marketsResolved == false); _; } /// @notice checks the team exists modifier tokenExists(uint256 _tokenId) { require(_tokenId >= 0 && _tokenId < numberOfTokens, "This token does not exist"); _; } /// @notice what it says on the tin modifier amountNotZero(uint256 _dai) { require(_dai > 0, "Amount must be above zero"); _; } ////////////// VIEW FUNCTIONS ////////////// /// @dev used in testing only function getOwnerTrackerPrice(uint256 _tokenId, uint256 _index) public view returns (uint256) { return (ownerTracker[_tokenId][_index].price); } /// @dev used in testing only function getOwnerTrackerAddress(uint256 _tokenId, uint256 _index) public view returns (address) { return (ownerTracker[_tokenId][_index].owner); } /// @dev called in collectRent function, and various other view functions function rentOwed(uint256 _tokenId) public view returns (uint256 augurFundsDue) { return price[_tokenId].mul(now.sub(timeLastCollected[_tokenId])).div(1 days); } /// @dev for front end only /// @return how much the current owner has deposited function liveDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); if(_rentOwed >= deposits[_tokenId][_currentOwner]) { return 0; } else { return deposits[_tokenId][_currentOwner].sub(_rentOwed); } } /// @dev for front end only /// @return how much the current user has deposited (note: user not owner) function userDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); if(_currentOwner == msg.sender) { if(_rentOwed >= deposits[_tokenId][msg.sender]) { return 0; } else { return deposits[_tokenId][msg.sender].sub(_rentOwed); } } else { return deposits[_tokenId][msg.sender]; } } /// @dev for front end only /// @return estimated rental expiry time function rentalExpiryTime(uint256 _tokenId) public view returns (uint256) { uint256 pps; pps = price[_tokenId].div(1 days); if (pps == 0) { return now; //if price is so low that pps = 0 just return current time as a fallback } else { return now + liveDepositAbleToWithdraw(_tokenId).div(pps); } } ////////////// AUGUR FUNCTIONS ////////////// // * internal * /// @notice send the Dai to Augur function _augurDeposit(uint256 _rentOwed) internal { augur.deposit(_rentOwed); } // * internal * /// @notice receive the Dai back from Augur function _augurWithdraw() internal { augur.withdraw(totalCollected); } // * internal * /// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET /// @notice checks if all X (x = number of tokens = number of teams) markets have resolved to either yes, no, or invalid /// @return true if yes, false if no function _haveAllAugurMarketsResolved() internal view returns(bool) { uint256 _resolvedOutcomesCount = 0; for (uint i = 0; i < numberOfTokens; i++) { // binary market has three outcomes: 0 (invalid), 1 (yes), 2 (no) if (market[i].getWinningPayoutNumerator(0) > 0 || market[i].getWinningPayoutNumerator(1) > 0 || market[i].getWinningPayoutNumerator(2) > 0 ) { _resolvedOutcomesCount = _resolvedOutcomesCount.add(1); } } // returns true if all resolved, false otherwise return (_resolvedOutcomesCount == numberOfTokens); } // * internal * /// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET /// @notice checks if all markets have resolved without conflicts or errors /// @return true if yes, false if no /// @dev this function will also set the winningOutcome variable function _haveAllAugurMarketsResolvedWithoutErrors() internal returns(bool) { uint256 _winningOutcomesCount = 0; uint256 _invalidOutcomesCount = 0; for (uint i = 0; i < numberOfTokens; i++) { if (market[i].getWinningPayoutNumerator(0) > 0) { _invalidOutcomesCount = _invalidOutcomesCount.add(1); } if (market[i].getWinningPayoutNumerator(1) > 0) { winningOutcome = i; // <- the winning outcome (a global variable) is set here _winningOutcomesCount = _winningOutcomesCount.add(1); } } return (_winningOutcomesCount == 1 && _invalidOutcomesCount == 0); } ////////////// DAI CONTRACT FUNCTIONS ////////////// // * internal * /// @notice common function for all outgoing DAI transfers function _sendCash(address _to, uint256 _amount) internal { require(cash.transfer(_to,_amount)); } // * internal * /// @notice common function for all incoming DAI transfers function _receiveCash(address _from, uint256 _amount) internal { require(cash.transferFrom(_from, address(this), _amount)); } // * internal * /// @return DAI balance of the contract /// @dev this is used to know how much exists to payout to winners function _getContractsCashBalance() internal view returns (uint256) { return cash.balanceOf(address(this)); } ////////////// MARKET RESOLUTION FUNCTIONS ////////////// /// @notice the first of three functions which must be called, one after the other, to conclude the competition /// @notice winnings can be paid out (or funds returned) only when these two steps are completed /// @notice this function checks whether the Augur markets have resolved, and if yes, whether they resolved correct or not /// @dev they are split into two sections due to the presence of step1BemergencyExit and step1CcircuitBreaker /// @dev can be called by anyone /// @dev can be called multiple times, but only once after markets have indeed resolved /// @dev the two arguments passed are for testing only function step1checkMarketsResolved() external { require(marketsResolved == false, "Step1 can only be completed once"); // first check if all X markets have all resolved one way or the other if (_haveAllAugurMarketsResolved()) { // do a final rent collection before the contract is locked down collectRentAllTokens(); // lock everything down marketsResolved = true; // now check if they all resolved without errors. It is set to false upon contract initialisation // this function also sets winningOutcome if there is one if (_haveAllAugurMarketsResolvedWithoutErrors()) { marketsResolvedWithoutErrors = true; } emit LogStep1Complete(true, winningOutcome, marketsResolvedWithoutErrors); } } /// @notice emergency function in case the augur markets never resolve for whatever reason /// @notice returns all funds to all users /// @notice can only be called 6 months after augur markets should have ended function step1BemergencyExit() external { require(marketsResolved == false, "Step1 can only be completed once"); require(now > (marketExpectedResolutionTime + 15778800), "Must wait 6 months for Augur Oracle"); collectRentAllTokens(); marketsResolved = true; emit LogStep1Complete(false, winningOutcome, false); } /// @notice Same as above, except that only I can call it, and I can call it whenever /// @notice to be clear, this only allows me to return all funds. I can not set a winner. function step1CcircuitBreaker() external { require(marketsResolved == false, "Step1 can only be completed once"); require(msg.sender == andrewsAddress, "Only owner can call this"); collectRentAllTokens(); marketsResolved = true; emit LogStep1Complete(false, winningOutcome, false); } /// @notice the second of the three functions which must be called, one after the other, to conclude the competition /// @dev gets funds back from Augur, gets the available funds for distribution /// @dev can be called by anyone, but only once function step2withdrawFromAugur() external { require(marketsResolved == true, "Must wait for market resolution"); require(step2Complete == false, "Step2 should only be run once"); step2Complete = true; uint256 _balanceBefore = _getContractsCashBalance(); _augurWithdraw(); uint256 _balanceAfter = _getContractsCashBalance(); // daiAvailableToDistribute therefore does not include unused deposits daiAvailableToDistribute = _balanceAfter.sub(_balanceBefore); emit LogStep2Complete(daiAvailableToDistribute); } /// @notice the final of the three functions which must be called, one after the other, to conclude the competition /// @notice pays me my 1% if markets resolved correctly. If not I don't deserve shit /// @dev this was originally included within step3 but it was modifed so that ineraction with Dai contract happened at the end function step3payAndrew() external { require(step2Complete == true, "Must wait for market resolution"); require(step3Complete == false, "Step3 should only be run once"); step3Complete = true; if (marketsResolvedWithoutErrors) { uint256 _andrewsWellEarntMonies = daiAvailableToDistribute.div(100); daiAvailableToDistribute = daiAvailableToDistribute.sub(_andrewsWellEarntMonies); _sendCash(andrewsAddress,_andrewsWellEarntMonies); emit LogAndrewPaid(_andrewsWellEarntMonies); } } /// @notice the final function of the competition resolution process. Pays out winnings, or returns funds, as necessary /// @dev users pull dai into their account. Replaces previous push vesion which required looping over unbounded mapping. function complete() external { require(step3Complete == true, "Step3 must be completed first"); if (marketsResolvedWithoutErrors) { _payoutWinnings(); } else { _returnRent(); } } // * internal * /// @notice pays winnings to the winners /// @dev must be internal and only called by complete function _payoutWinnings() internal { uint256 _winnersTimeHeld = timeHeld[winningOutcome][msg.sender]; if (_winnersTimeHeld > 0) { timeHeld[winningOutcome][msg.sender] = 0; // otherwise they can keep paying themselves over and over uint256 _numerator = daiAvailableToDistribute.mul(_winnersTimeHeld); uint256 _winningsToTransfer = _numerator.div(totalTimeHeld[winningOutcome]); _sendCash(msg.sender, _winningsToTransfer); emit LogWinningsPaid(msg.sender, _winningsToTransfer); } } // * internal * /// @notice returns all funds to users in case of invalid outcome /// @dev must be internal and only called by complete function _returnRent() internal { uint256 _rentCollected = collectedPerUser[msg.sender]; if (_rentCollected > 0) { collectedPerUser[msg.sender] = 0; // otherwise they can keep paying themselves over and over uint256 _numerator = daiAvailableToDistribute.mul(_rentCollected); uint256 _rentToToReturn = _numerator.div(totalCollected); _sendCash(msg.sender, _rentToToReturn); emit LogRentReturned(msg.sender, _rentToToReturn); } } /// @notice withdraw full deposit after markets have resolved /// @dev the other withdraw deposit functions are locked when markets have resolved so must use this one /// @dev ... which can only be called if markets have resolved. This function is also different in that it does /// @dev ... not attempt to collect rent or transfer ownership to a previous owner function withdrawDepositAfterResolution() external { require(marketsResolved == true, "step1 must be completed first"); for (uint i = 0; i < numberOfTokens; i++) { uint256 _depositToReturn = deposits[i][msg.sender]; if (_depositToReturn > 0) { deposits[i][msg.sender] = 0; _sendCash(msg.sender, _depositToReturn); emit LogDepositWithdrawal(_depositToReturn, i, msg.sender); } } } ////////////// ORDINARY COURSE OF BUSINESS FUNCTIONS ////////////// /// @notice collects rent for all tokens /// @dev makes it easy for me to call whenever I want to keep people paying their rent, thus cannot be internal /// @dev cannot be external because it is called within the step1 functions, therefore public function collectRentAllTokens() public notResolved() { for (uint i = 0; i < numberOfTokens; i++) { _collectRent(i); } } /// @notice collects rent for a specific token /// @dev also calculates and updates how long the current user has held the token for /// @dev called frequently internally, so cant be external. /// @dev is not a problem if called externally, but making internal to save gas function _collectRent(uint256 _tokenId) internal notResolved() { //only collect rent if the token is owned (ie, if owned by the contract this implies unowned) if (team.ownerOf(_tokenId) != address(this)) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); uint256 _timeOfThisCollection; if (_rentOwed >= deposits[_tokenId][_currentOwner]) { // run out of deposit. Calculate time it was actually paid for, then revert to previous owner _timeOfThisCollection = timeLastCollected[_tokenId].add(((now.sub(timeLastCollected[_tokenId])).mul(deposits[_tokenId][_currentOwner]).div(_rentOwed))); _rentOwed = deposits[_tokenId][_currentOwner]; // take what's left _revertToPreviousOwner(_tokenId); } else { // normal collection _timeOfThisCollection = now; } // decrease deposit by rent owed deposits[_tokenId][_currentOwner] = deposits[_tokenId][_currentOwner].sub(_rentOwed); // the 'important bit', where the duration the token has been held by each user is updated // it is essential that timeHeld and totalTimeHeld are incremented together such that the sum of // the first is equal to the second uint256 _timeHeldToIncrement = (_timeOfThisCollection.sub(timeLastCollected[_tokenId])); //just for readability timeHeld[_tokenId][_currentOwner] = timeHeld[_tokenId][_currentOwner].add(_timeHeldToIncrement); totalTimeHeld[_tokenId] = totalTimeHeld[_tokenId].add(_timeHeldToIncrement); // it is also essential that collectedPerUser and totalCollected are all incremented together // such that the sum of the first two (individually) is equal to the third collectedPerUser[_currentOwner] = collectedPerUser[_currentOwner].add(_rentOwed); totalCollected = totalCollected.add(_rentOwed); _augurDeposit(_rentOwed); emit LogRentCollection(_rentOwed, _tokenId); } // timeLastCollected is updated regardless of whether the token is owned, so that the clock starts ticking // ... when the first owner buys it, because this function is run before ownership changes upon calling // ... newRental timeLastCollected[_tokenId] = now; } /// @notice to rent a token function newRental(uint256 _newPrice, uint256 _tokenId, uint256 _deposit) external tokenExists(_tokenId) amountNotZero(_deposit) notResolved() { require(_newPrice > price[_tokenId], "Price must be higher than current price"); _collectRent(_tokenId); // require(1==2, "STFU"); address _currentOwner = team.ownerOf(_tokenId); if (_currentOwner == msg.sender) { // bought by current owner (ie, token ownership does not change, so it is as if the current owner // ... called changePrice and depositDai seperately) _changePrice(_newPrice, _tokenId); _depositDai(_deposit, _tokenId); } else { // bought by different user (the normal situation) // deposits are updated via depositDai function if _currentOwner = msg.sender // therefore deposits only updated inside this else section deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_deposit); // update currentOwnerIndex and ownerTracker currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].add(1); ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].owner = msg.sender; // update timeAcquired for the front end timeAcquired[_tokenId] = now; _transferTokenTo(_currentOwner, msg.sender, _newPrice, _tokenId); _receiveCash(msg.sender, _deposit); emit LogNewRental(msg.sender, _newPrice, _tokenId); } } /// @notice add new dai deposit to an existing rental /// @dev it is possible a user's deposit could be reduced to zero following _collectRent /// @dev they would then increase their deposit despite no longer owning it /// @dev this is ok, they can withdraw via withdrawDeposit. function depositDai(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() { _collectRent(_tokenId); _depositDai(_dai, _tokenId); } /// @dev depositDai is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _depositDai(uint256 _dai, uint256 _tokenId) internal { deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_dai); _receiveCash(msg.sender, _dai); emit LogDepositIncreased(_dai, _tokenId, msg.sender); } /// @notice increase the price of an existing rental /// @dev can't be external because also called within newRental function changePrice(uint256 _newPrice, uint256 _tokenId) public tokenExists(_tokenId) notResolved() { require(_newPrice > price[_tokenId], "New price must be higher than current price"); require(msg.sender == team.ownerOf(_tokenId), "Not owner"); _collectRent(_tokenId); _changePrice(_newPrice, _tokenId); } /// @dev changePrice is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _changePrice(uint256 _newPrice, uint256 _tokenId) internal { // below is the only instance when price is modifed outside of the _transferTokenTo function price[_tokenId] = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; emit LogPriceChange(price[_tokenId], _tokenId); } /// @notice withdraw deposit /// @dev do not need to be the current owner function withdrawDeposit(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() returns (uint256) { _collectRent(_tokenId); // if statement needed because deposit may have just reduced to zero following _collectRent if (deposits[_tokenId][msg.sender] > 0) { _withdrawDeposit(_dai, _tokenId); emit LogDepositWithdrawal(_dai, _tokenId, msg.sender); } } /// @notice withdraw full deposit /// @dev do not need to be the current owner function exit(uint256 _tokenId) external tokenExists(_tokenId) notResolved() { _collectRent(_tokenId); // if statement needed because deposit may have just reduced to zero following _collectRent modifier if (deposits[_tokenId][msg.sender] > 0) { _withdrawDeposit(deposits[_tokenId][msg.sender], _tokenId); emit LogExit(_tokenId); } } /* internal */ /// @notice actually withdraw the deposit and call _revertToPreviousOwner if necessary function _withdrawDeposit(uint256 _dai, uint256 _tokenId) internal { require(deposits[_tokenId][msg.sender] >= _dai, 'Withdrawing too much'); deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].sub(_dai); address _currentOwner = team.ownerOf(_tokenId); if(_currentOwner == msg.sender && deposits[_tokenId][msg.sender] == 0) { _revertToPreviousOwner(_tokenId); } _sendCash(msg.sender, _dai); } /* internal */ /// @notice if a users deposit runs out, either return to previous owner or foreclose function _revertToPreviousOwner(uint256 _tokenId) internal { bool _reverted = false; bool _toForeclose = false; uint256 _index; address _previousOwner; while (_reverted == false) { assert(currentOwnerIndex[_tokenId] >=0); currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].sub(1); // currentOwnerIndex will now point to previous owner _index = currentOwnerIndex[_tokenId]; // just for readability _previousOwner = ownerTracker[_tokenId][_index].owner; //if no previous owners. price -> zero, foreclose //if previous owner still has a deposit, transfer to them, update the price to what it used to be if (_index == 0) { _toForeclose = true; _reverted = true; } else if (deposits[_tokenId][_previousOwner] > 0) { _reverted = true; } } if (_toForeclose) { _foreclose(_tokenId); } else { address _currentOwner = team.ownerOf(_tokenId); uint256 _oldPrice = ownerTracker[_tokenId][_index].price; _transferTokenTo(_currentOwner, _previousOwner, _oldPrice, _tokenId); emit LogReturnToPreviousOwner(_tokenId, _previousOwner); } } /* internal */ /// @notice return token to the contract and return price to zero function _foreclose(uint256 _tokenId) internal { address _currentOwner = team.ownerOf(_tokenId); // third field is price, ie price goes to zero _transferTokenTo(_currentOwner, address(this), 0, _tokenId); emit LogForeclosure(_currentOwner, _tokenId); } /* internal */ /// @notice transfer ERC 721 between users /// @dev there is no event emitted as this is handled in ERC721.sol function _transferTokenTo(address _currentOwner, address _newOwner, uint256 _newPrice, uint256 _tokenId) internal { require(_currentOwner != address(0) && _newOwner != address(0) , "Cannot send to/from zero address"); team.transferFrom(_currentOwner, _newOwner, _tokenId); price[_tokenId] = _newPrice; } }
* internal * @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET @notice checks if all markets have resolved without conflicts or errors @return true if yes, false if no @dev this function will also set the winningOutcome variable
function _haveAllAugurMarketsResolvedWithoutErrors() internal returns(bool) { uint256 _winningOutcomesCount = 0; uint256 _invalidOutcomesCount = 0; for (uint i = 0; i < numberOfTokens; i++) { if (market[i].getWinningPayoutNumerator(0) > 0) { _invalidOutcomesCount = _invalidOutcomesCount.add(1); } if (market[i].getWinningPayoutNumerator(1) > 0) { _winningOutcomesCount = _winningOutcomesCount.add(1); } } return (_winningOutcomesCount == 1 && _invalidOutcomesCount == 0); }
15,828,447
[ 1, 7236, 282, 20676, 13690, 21641, 4269, 9722, 1157, 22130, 2056, 6229, 28235, 43, 1099, 1624, 1584, 225, 4271, 309, 777, 2267, 2413, 1240, 4640, 2887, 14450, 578, 1334, 327, 638, 309, 12465, 16, 629, 309, 1158, 225, 333, 445, 903, 2546, 444, 326, 5657, 2093, 19758, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 21516, 1595, 37, 637, 295, 3882, 2413, 12793, 8073, 4229, 1435, 2713, 1135, 12, 6430, 13, 288, 27699, 3639, 2254, 5034, 389, 8082, 2093, 1182, 10127, 1380, 273, 374, 31, 203, 3639, 2254, 5034, 389, 5387, 1182, 10127, 1380, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 7922, 5157, 31, 277, 27245, 288, 203, 5411, 309, 261, 27151, 63, 77, 8009, 588, 18049, 2093, 52, 2012, 2578, 7385, 12, 20, 13, 405, 374, 13, 288, 203, 7734, 389, 5387, 1182, 10127, 1380, 273, 389, 5387, 1182, 10127, 1380, 18, 1289, 12, 21, 1769, 203, 5411, 289, 203, 5411, 309, 261, 27151, 63, 77, 8009, 588, 18049, 2093, 52, 2012, 2578, 7385, 12, 21, 13, 405, 374, 13, 288, 203, 7734, 389, 8082, 2093, 1182, 10127, 1380, 273, 389, 8082, 2093, 1182, 10127, 1380, 18, 1289, 12, 21, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 327, 261, 67, 8082, 2093, 1182, 10127, 1380, 422, 404, 597, 389, 5387, 1182, 10127, 1380, 422, 374, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "openzeppelin-solidity/contracts/GSN/Context.sol"; import "./access/MultiOwnable.sol"; import "./IQV.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/utils/Address.sol"; import "./token/CVT.sol"; import "./random/Random.sol"; /** * @title PQV * @dev Implementation of the {IQV} abstract contract based on 'PQV' method. * * Probablistic quadratic voting, PQV, is the mitigation of 'Sybil attack'. * See the paper 'Secure Voting System with Sybil Attack Resistance using * Probabilistic Quadratic Voting and Trusted Execution Environment' for * advanced. */ contract PQV is Context, MultiOwnable, IQV { using SafeMath for uint256; using Address for address; struct Voter { uint256 weights; bool voted; // if true, that person already voted } struct Proposal { // If you can limit the length to a certain number of bytes, // always use one of bytes1 to bytes32 because they are much cheaper bytes32 name; // short name (up to 32 bytes) uint256[] voteCounts; // number of accumulated votes (sqrt-ed) } struct Ballot { bytes32 name; uint256 currentTime; uint256 timeLimit; Proposal[] proposals; mapping(address => Voter) voters; bool ended; uint256 winningProposal; } address private _CVTAddress; address private _randomAddress; bytes4 private constant BURNFROM = bytes4(keccak256(bytes('burnFrom(address,uint256)'))); bytes4 private constant RANDOM = bytes4(keccak256(bytes('random()'))); uint8 private constant OWNERBLE = 7; uint8 private constant ADDRESS = 7; uint8 private constant EXPONENT = 6; uint8 private constant TIMELIMIT = 5; uint256 private _exponent = 2; uint256 private _minimumTimeLimit = 1 hours; Ballot[] private _ballots; /** * @dev Sets the 'CVT' and 'Random' contracts. * * Requirements: * * - the `CVTAddress` MUST be a contract address. * - the `initialRandomAddress` MUST be a contract address. */ constructor ( address initialCVTAddress, address initialRandomAddress ) public { // conditions require(initialCVTAddress.isContract(), "NOT a contract address."); require(initialRandomAddress.isContract(), "NOT a contract address."); _CVTAddress = initialCVTAddress; // CVT contract _randomAddress = initialRandomAddress; // Random contract } /** * @dev Creates the ballot with `ballotName` and * `proposalNames` which is the array of each proposal's name. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an one or multiple {Create} event(s). */ function createBallot( bytes32 ballotName, bytes32[] calldata proposalNames ) external override returns (bool) { _createBallot(ballotName, proposalNames, _minimumTimeLimit); return true; } /** * @dev Creates the ballot with `ballotName`, `proposalNames`, and * `ballotTimeLimit` which is the time (seconds) when vote ends. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an one or multiple {Create} event(s). * * Requirements: * * - `ballotTimeLimit` >= `_minimumTimeLimit` */ function createBallot( bytes32 ballotName, bytes32[] calldata proposalNames, uint256 ballotTimeLimit ) external returns (bool) { _createBallot(ballotName, proposalNames, ballotTimeLimit); return true; } /** * @dev Creates the ballot with `ballotName`, `proposalNames`, and `ballotTimeLimit`. * Also it reserves random campaign via {_randomAddress}. * * This is internal function is equivalent to {createBallot}. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an one or multiple {Create} event(s). */ function _createBallot( bytes32 ballotName, bytes32[] memory proposalNames, uint256 ballotTimeLimit ) internal { // conditions require( ballotTimeLimit >= _minimumTimeLimit, "`ballotTimeLimit` MUST be higher than or at least same as `_minimumTimeLimit`." ); _ballots.push(); Ballot storage ballot = _ballots[_ballots.length - 1]; ballot.name = ballotName; ballot.currentTime = now; ballot.timeLimit = ballotTimeLimit; for (uint256 i = 0; i < proposalNames.length; i++) { ballot.proposals.push(Proposal({ name: proposalNames[i], voteCounts: new uint256[](0) })); emit Create(ballotName, proposalNames[i]); } } /** * @dev Joins in the `ballotNum`-th ballot by burning `amount` of tokens. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Join} event. * * Requirements: * * - the caller MUST NOT vote the ballot before. * - `ballotNum` cannot be out of the range of array. * - the caller MUST have a balance of at least `amount`. */ function joinAt( uint256 ballotNum, uint256 amount ) public override returns (bool) { Ballot storage ballot = _ballots[ballotNum]; // conditions require(!ballot.ended, "The ballot is ended."); require(ballot.currentTime + ballot.timeLimit > now, "Exceed time limit."); require(!ballot.voters[_msgSender()].voted, "You already voted."); (bool check, bytes memory data) = _CVTAddress.call( abi.encodeWithSelector(BURNFROM, _msgSender(), amount) ); require( check && (data.length == 0 || abi.decode(data, (bool))), "call burnFrom(address, uint256) is failed." ); ballot.voters[_msgSender()].weights = ballot.voters[_msgSender()].weights.add(amount); emit Join(_msgSender(), ballotNum, amount); return true; } /** * @dev Votes at the `proposals` with using `weights` tokens in the `ballotNum`-th ballot. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an one or multiple {Vote} event(s). * * Requirements: * * - the caller MUST NOT vote the ballot before. * - `ballotNum` cannot be out of the range of array. * - each element of `proposals` cannot be out of the range of array. * - the caller MUST have a balance of at least sum of `weights`. */ function voteAt( uint256 ballotNum, uint256[] calldata proposals_, uint256[] calldata weights_ ) external override returns (bool) { Ballot storage ballot = _ballots[ballotNum]; Voter storage sender = ballot.voters[_msgSender()]; // conditions require(!ballot.ended, "The ballot is ended."); require(ballot.currentTime + ballot.timeLimit > now, "Exceed time limit."); require(!sender.voted, "You already voted."); require(_sum(weights_) <= sender.weights, "Exceed the rights."); sender.voted = true; // If 'i' is out of the range of the array, // this will throw automatically and revert all changes for (uint256 i = 0; i < proposals_.length; i++) { ballot.proposals[proposals_[i]].voteCounts.push(weights_[i]); emit Vote(_msgSender(), ballotNum, proposals_[i], weights_[i]); } return true; } /** * @dev ends the `ballotNum`-th ballot. * * Returns a boolean value indicating whether the operation succeeded. * * Requirements: * * - `ballotNum` cannot be out of the range of array. * - `ballotNum`-th ballot's `timeLimit` SHOULD be exceed. * - at least one voting is needed. */ function tallyUp( uint256 ballotNum ) public returns (bool) { Ballot storage ballot = _ballots[ballotNum]; // conditions require(!ballot.ended, "Already ended."); require(ballot.currentTime + ballot.timeLimit <= now, "Not yet."); uint256 totalVoteCount = _totalVoteCountOf(ballotNum); require(totalVoteCount != 0, "Nobody voted."); ballot.ended = true; uint256 winningVoteCount = 0; uint256 voteCount = 0; while (winningVoteCount == 0) { // until non-zero for (uint256 p = 0; p < ballot.proposals.length; p++) { Proposal storage proposal = ballot.proposals[p]; voteCount = 0; for (uint256 v = 0; v < proposal.voteCounts.length; v++) { // PQV voteCount = voteCount.add( _probablistic( proposal.voteCounts[v], totalVoteCount, _exponent ) ); } if ( voteCount > winningVoteCount ) { // new winning proposal winningVoteCount = voteCount; ballot.winningProposal = p; } else if ( (voteCount != 0) && (voteCount == winningVoteCount) ) { // pick randomly (bool check, bytes memory data) = address(_randomAddress).call( abi.encodeWithSelector(RANDOM) ); require( check && (data.length != 0), "call random() is failed." ); uint256 returnValue = abi.decode(data, (uint256)); if (returnValue.mod(2) == 1) { winningVoteCount = voteCount; ballot.winningProposal = p; } } } } return true; } /** * @dev Computes probability of voting. */ function _probablistic( uint256 voteCount, uint256 totalVoteCount, uint256 exponent_ ) internal returns (uint256) { uint256 numerator = _pow(voteCount, exponent_); if (numerator >= totalVoteCount) { return _sqrt(voteCount); } else { (bool check, bytes memory data) = address(_randomAddress).call( abi.encodeWithSelector(RANDOM) ); require( check && (data.length != 0), "call random() is failed." ); uint256 returnValue = abi.decode(data, (uint256)); if (numerator > returnValue.mod(totalVoteCount)) { return _sqrt(voteCount); } } return 0; } /** * @dev Computes total votes in the `ballotNum`-th ballot. */ function _totalVoteCountOf( uint256 ballotNum ) internal view returns (uint256 totalVoteCounts_) { Ballot storage ballot = _ballots[ballotNum]; for (uint256 i=0; i<ballot.proposals.length; i++) { totalVoteCounts_ = totalVoteCounts_.add(_sum(ballot.proposals[i].voteCounts)); } } /** * @dev Returns the amount of ballots in existence. * * Only himself. */ function voterAt( uint256 ballotNum ) public view override returns ( uint256 weights_, bool voted_ ) { Ballot storage ballot = _ballots[ballotNum]; weights_ = ballot.voters[_msgSender()].weights; voted_ = ballot.voters[_msgSender()].voted; } /** * @dev Returns the amount of ballots in existence. */ function totalBallots( ) public view override returns ( uint256 length_ ) { length_ = _ballots.length; } /** * @dev Returns the number of the proposals. */ function proposalsLengthOf( uint256 ballotNum ) public view override returns ( uint256 length_ ) { length_ = _ballots[ballotNum].proposals.length; } /** * @dev Returns the array of names of the proposals. * * TODO: Returns accumulated expected values. */ function proposalsOf( uint256 ballotNum ) public view override returns ( bytes32[] memory names_ ) { uint256 length_ = proposalsLengthOf(ballotNum); names_ = new bytes32[](length_); for (uint256 i=0; i<length_; i++) { names_[i] = proposalOf(ballotNum, i); } } /** * @dev Returns the name of the proposal. * * TODO: Returns accumulated expected value. */ function proposalOf( uint256 ballotNum, uint256 proposalNum ) public view override returns ( bytes32 name_ ) { Proposal storage proposal = _ballots[ballotNum].proposals[proposalNum]; name_ = proposal.name; } /** * @dev Computes or gets the winning proposal. * * Requirements: * * - ballot MUST be ended. */ function winningProposalOf( uint256 ballotNum ) public view override returns ( uint256 winningProposal_ ) { Ballot storage ballot = _ballots[ballotNum]; require(ballot.ended, "Not yet."); winningProposal_ = ballot.winningProposal; } /** * @dev Gets the winning proposal's name. * * Requirements: * * - ballot MUST have been ended before. */ function winnerNameOf( uint256 ballotNum ) public view override returns ( bytes32 winnerName_ ) { Ballot storage ballot = _ballots[ballotNum]; require(ballot.ended, "Not yet."); winnerName_ = ballot.proposals[winningProposalOf(ballotNum)].name; } /** * @dev Returns the `ballotNum`-th ballot. */ function getBallotOf( uint256 ballotNum ) public view returns ( bytes32 name_, uint256 currentTime_, uint256 timeLimit_, bool ended_, uint256 winningProposal_ ) { Ballot storage ballot = _ballots[ballotNum]; name_ = ballot.name; currentTime_ = ballot.currentTime; timeLimit_ = ballot.timeLimit; ended_ = ballot.ended; winningProposal_ = ballot.winningProposal; } /** * @dev Returns the number of exponent. */ function getExponent( // ... ) public view returns (uint256) { return _exponent; } /** * @dev Sets {_exponent} to a value other than the default one of 2. */ function setExponent( uint256 newExponent ) public onlyOwner(EXPONENT) { _exponent = newExponent; } /** * @dev Returns the minimum time limit. */ function getMinimumTimeLimit( // ... ) public view returns (uint256) { return _minimumTimeLimit; } /** * @dev Sets {_minimumTimeLimit} to a value * other than the default one of 1 hours. */ function setMinimumTimeLimit( uint256 newMinimumTimeLimit ) public onlyOwner(TIMELIMIT) { _minimumTimeLimit = newMinimumTimeLimit; } /** * @dev Returns the address of 'CVT' contract. */ function getCVTAddress( // ... ) public view returns (address) { return _CVTAddress; } /** * @dev Sets the 'CVT' via an address. * {newCVTAddress}. * * Requirements: * * - the `newCVTAddress` MUST be contract address. */ function setCVTAddress( address newCVTAddress ) public onlyOwner(ADDRESS) { require(newCVTAddress.isContract(), "NOT a contract address."); _CVTAddress = newCVTAddress; } /** * @dev Returns the address of 'Random' contract. */ function getRandomAddress( // ... ) public view returns (address) { return _randomAddress; } /** * @dev Sets the 'Random' contract via an address. * {newRandomAddress}. * * Requirements: * * - the `newRandomAddress` MUST be contract address. */ function setRandomAddress( address newRandomAddress ) public onlyOwner(ADDRESS) { require(newRandomAddress.isContract(), "NOT a contract address."); _randomAddress = newRandomAddress; } /** * @dev Computes power. * * `a` ** 'b'. */ function _pow( uint256 a, uint256 b ) internal pure returns (uint256) { if (a == 0) { return 0; } if (a == 1) { return 1; } if (b == 0) { return 1; } if (b == 1) { return a; } uint256 c = a ** b; require(c > a, "SafeMath: power overflow"); return c; } /** * @dev Computes sqrt of `x`. */ function _sqrt( uint256 x ) internal pure returns ( uint256 y ) { uint256 z = x.add(1).div(2); y = x; while (z < y) { y = z; z = x.div(z).add(z).div(2); } } /** * @dev Computes summation of array `list`. */ function _sum( uint256[] memory list ) internal pure returns ( uint256 sum_ ) { for(uint256 i=0; i<list.length; i++) { sum_ = sum_.add(list[i]); } } /** * @dev Converts uint256 to int256 * * TODO: Safe type casting. */ function _uint256ToInt256( uint256 x ) internal pure returns ( int256 y ) { y = int256(x); } /** * @dev Calls {_addOwnership}. */ function addOwnership( address account, uint8 level ) public virtual onlyOwner(OWNERBLE) returns (bool) { _addOwnership(account, level); return true; } /** * @dev Calls {_deleteOwnership}. */ function deleteOwnership( address account ) public virtual onlyOwner(OWNERBLE) returns (bool) { _deleteOwnership(account); return true; } /** * @dev Calls {_transferOwnership}. */ function transferOwnership( address oldOwner, address newOwner ) public virtual onlyOwner(OWNERBLE) returns (bool) { _transferOwnership(oldOwner, newOwner); return true; } /** * @dev Calls {_changeOwnershipLevel}. */ function changeOwnershipLevel( address account, uint8 level ) public virtual onlyOwner(OWNERBLE) returns (bool) { _changeOwnershipLevel(account, level); return true; } }
number of accumulated votes (sqrt-ed)
uint256[] voteCounts;
15,809,841
[ 1, 2696, 434, 24893, 19588, 261, 24492, 17, 329, 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, 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, 3639, 2254, 5034, 8526, 12501, 9211, 31, 565, 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 ]
./partial_match/1/0xE891f654c2fB4653bA57eCdb3e38d8fe902153Fe/sources/MRG.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Merge Inu", "MRG") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 4; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 4; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
16,052,629
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 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 ]
[ 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, 3885, 1435, 4232, 39, 3462, 2932, 6786, 657, 89, 3113, 315, 49, 19380, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 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, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 1059, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 2 ]
./full_match/80001/0xdbD96F5a885B9B3515e9ca81683291aD72705A26/sources/contracts/Marketplace.sol
* @dev Get the marketplace fee percentage. @return The marketplace fee percentage./
function getMarketplaceFeePercentage() external view returns (uint256) { return marketplaceFeePercentage; }
5,572,257
[ 1, 967, 326, 29917, 14036, 11622, 18, 327, 1021, 29917, 14036, 11622, 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, 23232, 24577, 14667, 16397, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 29917, 14667, 16397, 31, 203, 565, 289, 203, 377, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; /** * @title SynthetixEscrow interface */ interface ISynthetixEscrow { function balanceOf(address account) public view returns (uint); function appendVestingEntry(address account, uint quantity) public; }
* @title SynthetixEscrow interface/
interface ISynthetixEscrow { function balanceOf(address account) public view returns (uint); function appendVestingEntry(address account, uint quantity) public; }
1,752,250
[ 1, 10503, 451, 278, 697, 6412, 492, 1560, 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, 5831, 4437, 878, 451, 278, 697, 6412, 492, 288, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 11890, 1769, 203, 203, 565, 445, 714, 58, 10100, 1622, 12, 2867, 2236, 16, 2254, 10457, 13, 1071, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x7EFaD749c69962F8BBB659196c22B5E64953507b/sources/contracts/escrow.sol
Закрытие аукциона от имени владельца контракта
function AcceptOffer(uint postId, address payable seller, uint price) public onlyOwners notPaused { AcceptOfferHandler(postId, seller, price, false); }
14,189,909
[ 1, 145, 250, 145, 113, 145, 123, 146, 227, 146, 238, 146, 229, 145, 121, 145, 118, 225, 145, 113, 146, 230, 145, 123, 146, 233, 145, 121, 145, 127, 145, 126, 145, 113, 225, 145, 127, 146, 229, 225, 145, 121, 145, 125, 145, 118, 145, 126, 145, 121, 225, 145, 115, 145, 124, 145, 113, 145, 117, 145, 118, 145, 124, 146, 239, 146, 233, 145, 113, 225, 145, 123, 145, 127, 145, 126, 146, 229, 146, 227, 145, 113, 145, 123, 146, 229, 145, 113, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8662, 10513, 12, 11890, 1603, 548, 16, 1758, 8843, 429, 29804, 16, 2254, 6205, 13, 1071, 1338, 5460, 414, 486, 28590, 288, 203, 202, 202, 5933, 10513, 1503, 12, 2767, 548, 16, 29804, 16, 6205, 16, 629, 1769, 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 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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"); } } } // 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) { 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.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() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/interfaces/IFarmFactory.sol interface IFarmFactory { function userEnteredFarm(address _user) external; function userLeftFarm(address _user) external; function addFarm(address _farmAddress) external; } // 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 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; } } // File: contracts/interfaces/IFarm.sol interface IFarm { function owner() external view returns (address); } // File: contracts/Vesting.sol contract Vesting is ReentrancyGuard { using SafeERC20 for IERC20; IERC20 public token; uint256 public vestingDuration; // 1170000 blocks ~ 180 days address public farm; struct VestingInfo { uint256 amount; uint256 startBlock; uint256 claimedAmount; } // user address => vestingInfo[] mapping(address => VestingInfo[]) private _userToVestingList; modifier onlyFarm() { require(msg.sender == farm, "Vesting: FORBIDDEN"); _; } modifier onlyFarmOwner() { require(msg.sender == IFarm(farm).owner(), "Vesting: FORBIDDEN"); _; } constructor(address _token, uint256 _vestingDuration) { token = IERC20(_token); require(_vestingDuration > 0, "Vesting: Invalid duration"); vestingDuration = _vestingDuration; farm = msg.sender; } function addVesting(address _user, uint256 _amount) external onlyFarm { token.safeTransferFrom(msg.sender, address(this), _amount); VestingInfo memory info = VestingInfo(_amount, block.number, 0); _userToVestingList[_user].push(info); } function claimVesting(uint256 _index) external nonReentrant { _claimVestingInternal(_index); } function claimTotalVesting() external nonReentrant { uint256 count = _userToVestingList[msg.sender].length; for (uint256 _index = 0; _index < count; _index++) { if (_getVestingClaimableAmount(msg.sender, _index) > 0) { _claimVestingInternal(_index); } } } function _claimVestingInternal(uint256 _index) internal { require(_index < _userToVestingList[msg.sender].length, "Vesting: Invalid index"); uint256 claimableAmount = _getVestingClaimableAmount(msg.sender, _index); require(claimableAmount > 0, "Vesting: Nothing to claim"); _userToVestingList[msg.sender][_index].claimedAmount = _userToVestingList[msg.sender][_index].claimedAmount + claimableAmount; require(token.transfer(msg.sender, claimableAmount), "Vesting: transfer failed"); } function _getVestingClaimableAmount(address _user, uint256 _index) internal view returns (uint256 claimableAmount) { VestingInfo memory info = _userToVestingList[_user][_index]; if (block.number <= info.startBlock) return 0; uint256 passedBlocks = block.number - info.startBlock; uint256 releasedAmount; if (passedBlocks >= vestingDuration) { releasedAmount = info.amount; } else { releasedAmount = (info.amount * passedBlocks) / vestingDuration; } claimableAmount = 0; if (releasedAmount > info.claimedAmount) { claimableAmount = releasedAmount - info.claimedAmount; } } function getVestingTotalClaimableAmount(address _user) external view returns (uint256 totalClaimableAmount) { uint256 count = _userToVestingList[_user].length; for (uint256 _index = 0; _index < count; _index++) { totalClaimableAmount = totalClaimableAmount + _getVestingClaimableAmount(_user, _index); } } function getVestingClaimableAmount(address _user, uint256 _index) external view returns (uint256) { return _getVestingClaimableAmount(_user, _index); } function getVestingsCountByUser(address _user) external view returns (uint256) { uint256 count = _userToVestingList[_user].length; return count; } function getVestingInfo(address _user, uint256 _index) external view returns (VestingInfo memory) { require(_index < _userToVestingList[_user].length, "Vesting: Invalid index"); VestingInfo memory info = _userToVestingList[_user][_index]; return info; } function getTotalAmountLockedByUser(address _user) external view returns (uint256) { uint256 count = _userToVestingList[_user].length; uint256 amountLocked = 0; for (uint256 _index = 0; _index < count; _index++) { amountLocked = amountLocked + _userToVestingList[_user][_index].amount - _userToVestingList[_user][_index].claimedAmount; } return amountLocked; } function updateVestingDuration(uint256 _vestingDuration) external onlyFarmOwner { vestingDuration = _vestingDuration; } } // SPDX-License-Identifier: GPL-3.0 // File: contracts/Farm.sol contract Farm { using SafeERC20 for IERC20; /// @notice information stuct on each user than stakes LP tokens. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. } address public owner; IERC20 public lpToken; IERC20 public rewardToken; uint256 public startBlock; uint256 public rewardPerBlock; uint256 public lastRewardBlock; uint256 public accRewardPerShare; uint256 public farmerCount; bool public isActive; uint256 public firstCycleRate; uint256 public initRate; uint256 public reducingRate; // 95 equivalent to 95% uint256 public reducingCycle; // 195000 equivalent 195000 block IFarmFactory public factory; address public farmGenerator; Vesting public vesting; uint256 public percentForVesting; // 50 equivalent to 50% /// @notice information on each user than stakes LP tokens mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); modifier onlyOwner() { require(msg.sender == owner, "Farm: FORBIDDEN"); _; } modifier mustActive() { require(isActive == true, "Farm: Not active"); _; } constructor(address _factory, address _farmGenerator) { factory = IFarmFactory(_factory); farmGenerator = _farmGenerator; } /** * @notice initialize the farming contract. This is called only once upon farm creation and the FarmGenerator ensures the farm has the correct paramaters */ function init( IERC20 _rewardToken, IERC20 _lpToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256[] memory _rateParameters, // 0: firstCycleRate , 1: initRate, 2: reducingRate, 3: reducingCycle uint256[] memory _vestingParameters, // 0: percentForVesting, 1: vestingDuration address _owner ) public { require(msg.sender == address(farmGenerator), "Farm: FORBIDDEN"); require(address(_rewardToken) != address(0), "Farm: Invalid reward token"); require(_rewardPerBlock > 1000, "Farm: Invalid block reward"); // minimum 1000 divisibility per block reward require(_startBlock > block.number, "Farm: Invalid start block"); // ideally at least 24 hours more to give farmers time require(_vestingParameters[0] <= 100, "Farm: Invalid percent for vesting"); require(_rateParameters[0] > 0, "Farm: Invalid first cycle rate"); require(_rateParameters[1] > 0, "Farm: Invalid initial rate"); require(_rateParameters[2] > 0 && _rateParameters[1] < 100, "Farm: Invalid reducing rate"); require(_rateParameters[3] > 0, "Farm: Invalid reducing cycle"); rewardToken = _rewardToken; startBlock = _startBlock; rewardPerBlock = _rewardPerBlock; firstCycleRate = _rateParameters[0]; initRate = _rateParameters[1]; reducingRate = _rateParameters[2]; reducingCycle = _rateParameters[3]; isActive = true; owner = _owner; uint256 _lastRewardBlock = block.number > _startBlock ? block.number : _startBlock; lpToken = _lpToken; lastRewardBlock = _lastRewardBlock; accRewardPerShare = 0; if (_vestingParameters[0] > 0) { percentForVesting = _vestingParameters[0]; vesting = new Vesting(address(_rewardToken), _vestingParameters[1]); _rewardToken.safeApprove(address(vesting), type(uint256).max); } } /** * @notice Gets the reward multiplier over the given _fromBlock until _to block * @param _fromBlock the start of the period to measure rewards for * @param _toBlock the end of the period to measure rewards for * @return The weighted multiplier for the given period */ function getMultiplier(uint256 _fromBlock, uint256 _toBlock) public view returns (uint256) { return _getMultiplierFromStart(_toBlock) - _getMultiplierFromStart(_fromBlock); } function _getMultiplierFromStart(uint256 _block) internal view returns (uint256) { uint256 roundPassed = (_block - startBlock) / reducingCycle; if (roundPassed == 0) { return (_block - startBlock) * firstCycleRate * 1e12; } else { uint256 multiplier = reducingCycle * firstCycleRate * 1e12; uint256 i = 0; for (i = 0; i < roundPassed - 1; i++) { multiplier = multiplier + ((1e12 * initRate * reducingRate**i) / 100**i) * reducingCycle; } if ((_block - startBlock) % reducingCycle > 0) { multiplier = multiplier + ((1e12 * initRate * reducingRate**i) / 100**i) * ((_block - startBlock) % reducingCycle); } return multiplier; } } /** * @notice function to see accumulated balance of reward token for specified user * @param _user the user for whom unclaimed tokens will be shown * @return total amount of withdrawable reward tokens */ function pendingReward(address _user) public view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 _accRewardPerShare = accRewardPerShare; uint256 _lpSupply = lpToken.balanceOf(address(this)); if (block.number > lastRewardBlock && _lpSupply != 0 && isActive == true) { uint256 _multiplier = getMultiplier(lastRewardBlock, block.number); uint256 _tokenReward = (_multiplier * rewardPerBlock) / 1e12; _accRewardPerShare = _accRewardPerShare + ((_tokenReward * 1e12) / _lpSupply); } return ((user.amount * _accRewardPerShare) / 1e12) - user.rewardDebt; } /** * @notice updates pool information to be up to date to the current block */ function updatePool() public mustActive { if (block.number <= lastRewardBlock) { return; } uint256 _lpSupply = lpToken.balanceOf(address(this)); if (_lpSupply == 0) { lastRewardBlock = block.number; return; } uint256 _multiplier = getMultiplier(lastRewardBlock, block.number); uint256 _tokenReward = (_multiplier * rewardPerBlock) / 1e12; accRewardPerShare = accRewardPerShare + ((_tokenReward * 1e12) / _lpSupply); lastRewardBlock = block.number; } /** * @notice deposit LP token function for msg.sender * @param _amount the total deposit amount */ function deposit(uint256 _amount) public mustActive { UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 _pending = ((user.amount * accRewardPerShare) / 1e12) - user.rewardDebt; uint256 availableRewardToken = rewardToken.balanceOf(address(this)); if (_pending > availableRewardToken) { _pending = availableRewardToken; } uint256 _forVesting = 0; if (percentForVesting > 0) { _forVesting = (_pending * percentForVesting) / 100; vesting.addVesting(msg.sender, _forVesting); } rewardToken.safeTransfer(msg.sender, _pending - _forVesting); } if (user.amount == 0 && _amount > 0) { factory.userEnteredFarm(msg.sender); farmerCount++; } lpToken.safeTransferFrom(msg.sender, address(this), _amount); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * accRewardPerShare) / 1e12; emit Deposit(msg.sender, _amount); } /** * @notice withdraw LP token function for msg.sender * @param _amount the total withdrawable amount */ function withdraw(uint256 _amount) public { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "INSUFFICIENT"); if (isActive == true) { updatePool(); } if (user.amount == _amount && _amount > 0) { factory.userLeftFarm(msg.sender); farmerCount--; } uint256 _pending = ((user.amount * accRewardPerShare) / 1e12) - user.rewardDebt; uint256 availableRewardToken = rewardToken.balanceOf(address(this)); if (_pending > availableRewardToken) { _pending = availableRewardToken; } uint256 _forVesting = 0; if (percentForVesting > 0) { _forVesting = (_pending * percentForVesting) / 100; vesting.addVesting(msg.sender, _forVesting); } rewardToken.safeTransfer(msg.sender, _pending - _forVesting); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * accRewardPerShare) / 1e12; lpToken.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } /** * @notice emergency functoin to withdraw LP tokens and forego harvest rewards. Important to protect users LP tokens */ function emergencyWithdraw() public { UserInfo storage user = userInfo[msg.sender]; lpToken.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, user.amount); if (user.amount > 0) { factory.userLeftFarm(msg.sender); farmerCount--; } user.amount = 0; user.rewardDebt = 0; } /** * @notice Safe reward transfer function, just in case a rounding error causes pool to not have enough reward tokens * @param _to the user address to transfer tokens to * @param _amount the total amount of tokens to transfer */ function _safeRewardTransfer(address _to, uint256 _amount) internal { rewardToken.transfer(_to, _amount); } function rescueFunds( address tokenToRescue, address to, uint256 amount ) external onlyOwner { require(address(lpToken) != tokenToRescue, "Farm: Cannot claim token held by the contract"); IERC20(tokenToRescue).safeTransfer(to, amount); } function updateReducingRate(uint256 _reducingRate) external onlyOwner mustActive { require(_reducingRate > 0 && _reducingRate <= 100, "Farm: Invalid reducing rate"); reducingRate = _reducingRate; } function updatePercentForVesting(uint256 _percentForVesting) external onlyOwner { require( _percentForVesting >= 0 && _percentForVesting <= 100, "Farm: Invalid percent for vesting" ); percentForVesting = _percentForVesting; } function forceEnd() external onlyOwner mustActive { updatePool(); isActive = false; } function transferOwnership(address _owner) external onlyOwner { owner = _owner; } }
195000 equivalent 195000 block
uint256 public reducingCycle;
13,608,490
[ 1, 31677, 3784, 7680, 24262, 3784, 1203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 9299, 2822, 13279, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; // File: contracts/NFTfi/v1/openzeppelin/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/NFTfi/v1/openzeppelin/Roles.sol /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: contracts/NFTfi/v1/openzeppelin/PauserRole.sol contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: contracts/NFTfi/v1/openzeppelin/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: contracts/NFTfi/v1/openzeppelin/ReentrancyGuard.sol /** * @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() 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; } /** * @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); } } // File: contracts/NFTfi/v1/NFTfiAdmin.sol pragma solidity ^0.5.16; // @title Admin contract for NFTfi. Holds owner-only functions to adjust // contract-wide fees, parameters, etc. // @author smartcontractdev.eth, creator of wrappedkitties.eth, cwhelper.eth, and // kittybounties.eth contract NFTfiAdmin is Ownable, Pausable, ReentrancyGuard { /* ****** */ /* EVENTS */ /* ****** */ // @notice This event is fired whenever the admins change the percent of // interest rates earned that they charge as a fee. Note that // newAdminFee can never exceed 10,000, since the fee is measured // in basis points. // @param newAdminFee - The new admin fee measured in basis points. This // is a percent of the interest paid upon a loan's completion that // go to the contract admins. event AdminFeeUpdated( uint256 newAdminFee ); /* ******* */ /* STORAGE */ /* ******* */ // @notice A mapping from from an ERC20 currency address to whether that // currency is whitelisted to be used by this contract. Note that // NFTfi only supports loans that use ERC20 currencies that are // whitelisted, all other calls to beginLoan() will fail. mapping (address => bool) public erc20CurrencyIsWhitelisted; // @notice A mapping from from an NFT contract's address to whether that // contract is whitelisted to be used by this contract. Note that // NFTfi only supports loans that use NFT collateral from contracts // that are whitelisted, all other calls to beginLoan() will fail. mapping (address => bool) public nftContractIsWhitelisted; // @notice The maximum duration of any loan started on this platform, // measured in seconds. This is both a sanity-check for borrowers // and an upper limit on how long admins will have to support v1 of // this contract if they eventually deprecate it, as well as a check // to ensure that the loan duration never exceeds the space alotted // for it in the loan struct. uint256 public maximumLoanDuration = 53 weeks; // @notice The maximum number of active loans allowed on this platform. // This parameter is used to limit the risk that NFTfi faces while // the project is first getting started. uint256 public maximumNumberOfActiveLoans = 100; // @notice The percentage of interest earned by lenders on this platform // that is taken by the contract admin's as a fee, measured in // basis points (hundreths of a percent). uint256 public adminFeeInBasisPoints = 25; /* *********** */ /* CONSTRUCTOR */ /* *********** */ constructor() internal { // Whitelist mainnet WETH erc20CurrencyIsWhitelisted[address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)] = true; // Whitelist mainnet DAI erc20CurrencyIsWhitelisted[address(0x6B175474E89094C44Da98b954EedeAC495271d0F)] = true; // Whitelist mainnet CryptoKitties nftContractIsWhitelisted[address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)] = true; } /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @dev Gets the token name * @return string representing the token name */ function name() external pure returns (string memory) { return "NFTfi Promissory Note"; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external pure returns (string memory) { return "NFTfi"; } // @notice This function can be called by admins to change the whitelist // status of an ERC20 currency. This includes both adding an ERC20 // currency to the whitelist and removing it. // @param _erc20Currency - The address of the ERC20 currency whose whitelist // status changed. // @param _setAsWhitelisted - The new status of whether the currency is // whitelisted or not. function whitelistERC20Currency(address _erc20Currency, bool _setAsWhitelisted) external onlyOwner { erc20CurrencyIsWhitelisted[_erc20Currency] = _setAsWhitelisted; } // @notice This function can be called by admins to change the whitelist // status of an NFT contract. This includes both adding an NFT // contract to the whitelist and removing it. // @param _nftContract - The address of the NFT contract whose whitelist // status changed. // @param _setAsWhitelisted - The new status of whether the contract is // whitelisted or not. function whitelistNFTContract(address _nftContract, bool _setAsWhitelisted) external onlyOwner { nftContractIsWhitelisted[_nftContract] = _setAsWhitelisted; } // @notice This function can be called by admins to change the // maximumLoanDuration. Note that they can never change // maximumLoanDuration to be greater than UINT32_MAX, since that's // the maximum space alotted for the duration in the loan struct. // @param _newMaximumLoanDuration - The new maximum loan duration, measured // in seconds. function updateMaximumLoanDuration(uint256 _newMaximumLoanDuration) external onlyOwner { require(_newMaximumLoanDuration <= uint256(~uint32(0)), 'loan duration cannot exceed space alotted in struct'); maximumLoanDuration = _newMaximumLoanDuration; } // @notice This function can be called by admins to change the // maximumNumberOfActiveLoans. // @param _newMaximumNumberOfActiveLoans - The new maximum number of // active loans, used to limit the risk that NFTfi faces while the // project is first getting started. function updateMaximumNumberOfActiveLoans(uint256 _newMaximumNumberOfActiveLoans) external onlyOwner { maximumNumberOfActiveLoans = _newMaximumNumberOfActiveLoans; } // @notice This function can be called by admins to change the percent of // interest rates earned that they charge as a fee. Note that // newAdminFee can never exceed 10,000, since the fee is measured // in basis points. // @param _newAdminFeeInBasisPoints - The new admin fee measured in basis points. This // is a percent of the interest paid upon a loan's completion that // go to the contract admins. function updateAdminFee(uint256 _newAdminFeeInBasisPoints) external onlyOwner { require(_newAdminFeeInBasisPoints <= 10000, 'By definition, basis points cannot exceed 10000'); adminFeeInBasisPoints = _newAdminFeeInBasisPoints; emit AdminFeeUpdated(_newAdminFeeInBasisPoints); } } // File: contracts/NFTfi/v1/openzeppelin/ECDSA.sol /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // 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))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: contracts/NFTfi/v1/NFTfiSigningUtils.sol pragma solidity ^0.5.16; // @title Helper contract for NFTfi. This contract manages verifying signatures // from off-chain NFTfi orders. // @author smartcontractdev.eth, creator of wrappedkitties.eth, cwhelper.eth, // and kittybounties.eth // @notice Cite: I found the following article very insightful while creating // this contract: // https://dzone.com/articles/signing-and-verifying-ethereum-signatures // @notice Cite: I also relied on this article somewhat: // https://forum.openzeppelin.com/t/sign-it-like-you-mean-it-creating-and-verifying-ethereum-signatures/697 contract NFTfiSigningUtils { /* *********** */ /* CONSTRUCTOR */ /* *********** */ constructor() internal {} /* ********* */ /* FUNCTIONS */ /* ********* */ // @notice OpenZeppelin's ECDSA library is used to call all ECDSA functions // directly on the bytes32 variables themselves. using ECDSA for bytes32; // @notice This function gets the current chain ID. function getChainID() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } // @notice This function is called in NFTfi.beginLoan() to validate the // borrower's signature that the borrower provided off-chain to // verify that they did indeed want to use this NFT for this loan. // @param _nftCollateralId - The ID within the NFTCollateralContract for // the NFT being used as collateral for this loan. The NFT is // stored within this contract during the duration of the loan. // @param _borrowerNonce - The nonce referred to here // is not the same as an Ethereum account's nonce. We are referring // instead to nonces that are used by both the lender and the // borrower when they are first signing off-chain NFTfi orders. // These nonces can be any uint256 value that the user has not // previously used to sign an off-chain order. Each nonce can be // used at most once per user within NFTfi, regardless of whether // they are the lender or the borrower in that situation. This // serves two purposes. First, it prevents replay attacks where an // attacker would submit a user's off-chain order more than once. // Second, it allows a user to cancel an off-chain order by calling // NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the // nonce as used and prevents any future loan from using the user's // off-chain order that contains that nonce. // @param _nftCollateralContract - The ERC721 contract of the NFT // collateral // @param _borrower - The address of the borrower. // @param _borrowerSignature - The ECDSA signature of the borrower, // obtained off-chain ahead of time, signing the following // combination of parameters: _nftCollateralId, _borrowerNonce, // _nftCollateralContract, _borrower. // @return A bool representing whether verification succeeded, showing that // this signature matched this address and parameters. function isValidBorrowerSignature( uint256 _nftCollateralId, uint256 _borrowerNonce, address _nftCollateralContract, address _borrower, bytes memory _borrowerSignature ) public view returns(bool) { if(_borrower == address(0)){ return false; } else { uint256 chainId; chainId = getChainID(); bytes32 message = keccak256(abi.encodePacked( _nftCollateralId, _borrowerNonce, _nftCollateralContract, _borrower, chainId )); bytes32 messageWithEthSignPrefix = message.toEthSignedMessageHash(); return (messageWithEthSignPrefix.recover(_borrowerSignature) == _borrower); } } // @notice This function is called in NFTfi.beginLoan() to validate the // lender's signature that the lender provided off-chain to // verify that they did indeed want to agree to this loan according // to these terms. // @param _loanPrincipalAmount - The original sum of money transferred // from lender to borrower at the beginning of the loan, measured // in loanERC20Denomination's smallest units. // @param _maximumRepaymentAmount - The maximum amount of money that the // borrower would be required to retrieve their collateral. If // interestIsProRated is set to false, then the borrower will // always have to pay this amount to retrieve their collateral. // @param _nftCollateralId - The ID within the NFTCollateralContract for // the NFT being used as collateral for this loan. The NFT is // stored within this contract during the duration of the loan. // @param _loanDuration - The amount of time (measured in seconds) that can // elapse before the lender can liquidate the loan and seize the // underlying collateral NFT. // @param _loanInterestRateForDurationInBasisPoints - The interest rate // (measured in basis points, e.g. hundreths of a percent) for the // loan, that must be repaid pro-rata by the borrower at the // conclusion of the loan or risk seizure of their nft collateral. // @param _adminFeeInBasisPoints - The percent (measured in basis // points) of the interest earned that will be taken as a fee by // the contract admins when the loan is repaid. The fee is stored // in the loan struct to prevent an attack where the contract // admins could adjust the fee right before a loan is repaid, and // take all of the interest earned. // @param _lenderNonce - The nonce referred to here // is not the same as an Ethereum account's nonce. We are referring // instead to nonces that are used by both the lender and the // borrower when they are first signing off-chain NFTfi orders. // These nonces can be any uint256 value that the user has not // previously used to sign an off-chain order. Each nonce can be // used at most once per user within NFTfi, regardless of whether // they are the lender or the borrower in that situation. This // serves two purposes. First, it prevents replay attacks where an // attacker would submit a user's off-chain order more than once. // Second, it allows a user to cancel an off-chain order by calling // NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the // nonce as used and prevents any future loan from using the user's // off-chain order that contains that nonce. // @param _nftCollateralContract - The ERC721 contract of the NFT // collateral // @param _loanERC20Denomination - The ERC20 contract of the currency being // used as principal/interest for this loan. // @param _lender - The address of the lender. The lender can change their // address by transferring the NFTfi ERC721 token that they // received when the loan began. // @param _interestIsProRated - A boolean value determining whether the // interest will be pro-rated if the loan is repaid early, or // whether the borrower will simply pay maximumRepaymentAmount. // @param _lenderSignature - The ECDSA signature of the lender, // obtained off-chain ahead of time, signing the following // combination of parameters: _loanPrincipalAmount, // _maximumRepaymentAmount _nftCollateralId, _loanDuration, // _loanInterestRateForDurationInBasisPoints, _lenderNonce, // _nftCollateralContract, _loanERC20Denomination, _lender, // _interestIsProRated. // @return A bool representing whether verification succeeded, showing that // this signature matched this address and parameters. function isValidLenderSignature( uint256 _loanPrincipalAmount, uint256 _maximumRepaymentAmount, uint256 _nftCollateralId, uint256 _loanDuration, uint256 _loanInterestRateForDurationInBasisPoints, uint256 _adminFeeInBasisPoints, uint256 _lenderNonce, address _nftCollateralContract, address _loanERC20Denomination, address _lender, bool _interestIsProRated, bytes memory _lenderSignature ) public view returns(bool) { if(_lender == address(0)){ return false; } else { uint256 chainId; chainId = getChainID(); bytes32 message = keccak256(abi.encodePacked( _loanPrincipalAmount, _maximumRepaymentAmount, _nftCollateralId, _loanDuration, _loanInterestRateForDurationInBasisPoints, _adminFeeInBasisPoints, _lenderNonce, _nftCollateralContract, _loanERC20Denomination, _lender, _interestIsProRated, chainId )); bytes32 messageWithEthSignPrefix = message.toEthSignedMessageHash(); return (messageWithEthSignPrefix.recover(_lenderSignature) == _lender); } } } // File: contracts/NFTfi/v1/openzeppelin/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: contracts/NFTfi/v1/openzeppelin/IERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: contracts/NFTfi/v1/openzeppelin/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: contracts/NFTfi/v1/openzeppelin/SafeMath.sol /** * @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; } } // File: contracts/NFTfi/v1/openzeppelin/Address.sol /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/NFTfi/v1/openzeppelin/ERC165.sol /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // File: contracts/NFTfi/v1/openzeppelin/ERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner); _clearApproval(tokenId); _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: contracts/NFTfi/v1/openzeppelin/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { 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); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/NFTfi/v1/NFTfi.sol pragma solidity ^0.5.16; // @title Main contract for NFTfi. This contract manages the ability to create // NFT-backed peer-to-peer loans. // @author smartcontractdev.eth, creator of wrappedkitties.eth, cwhelper.eth, and // kittybounties.eth // @notice There are five steps needed to commence an NFT-backed loan. First, // the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi // contract to move their NFT's on their behalf. Second, the borrower // signs an off-chain message for each NFT that they would like to // put up for collateral. This prevents borrowers from accidentally // lending an NFT that they didn't mean to lend, due to approveAll() // approving their entire collection. Third, the lender calls // erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's // ERC20 tokens on their behalf. Fourth, the lender signs an off-chain // message, proposing the amount, rate, and duration of a loan for a // particular NFT. Fifth, the borrower calls NFTfi.beginLoan() to // accept these terms and enter into the loan. The NFT is stored in the // contract, the borrower receives the loan principal in the specified // ERC20 currency, and the lender receives an NFTfi promissory note (in // ERC721 form) that represents the rights to either the // principal-plus-interest, or the underlying NFT collateral if the // borrower does not pay back in time. The lender can freely transfer // and trade this ERC721 promissory note as they wish, with the // knowledge that transferring the ERC721 promissory note tranfsers the // rights to principal-plus-interest and/or collateral, and that they // will no longer have a claim on the loan. The ERC721 promissory note // itself represents that claim. // @notice A loan may end in one of two ways. First, a borrower may call // NFTfi.payBackLoan() and pay back the loan plus interest at any time, // in which case they receive their NFT back in the same transaction. // Second, if the loan's duration has passed and the loan has not been // paid back yet, a lender can call NFTfi.liquidateOverdueLoan(), in // which case they receive the underlying NFT collateral and forfeit // the rights to the principal-plus-interest, which the borrower now // keeps. // @notice If the loan was agreed to be a pro-rata interest loan, then the user // only pays the principal plus pro-rata interest if repaid early. // However, if the loan was agreed to be a fixed-repayment loan (by // specifying UINT32_MAX as the value for // loanInterestRateForDurationInBasisPoints), then the borrower pays // the maximumRepaymentAmount regardless of whether they repay early // or not. contract NFTfi is NFTfiAdmin, NFTfiSigningUtils, ERC721 { // @notice OpenZeppelin's SafeMath library is used for all arithmetic // operations to avoid overflows/underflows. using SafeMath for uint256; /* ********** */ /* DATA TYPES */ /* ********** */ // @notice The main Loan struct. The struct fits in six 256-bits words due // to Solidity's rules for struct packing. struct Loan { // A unique identifier for this particular loan, sourced from the // continuously increasing parameter totalNumLoans. uint256 loanId; // The original sum of money transferred from lender to borrower at the // beginning of the loan, measured in loanERC20Denomination's smallest // units. uint256 loanPrincipalAmount; // The maximum amount of money that the borrower would be required to // repay retrieve their collateral, measured in loanERC20Denomination's // smallest units. If interestIsProRated is set to false, then the // borrower will always have to pay this amount to retrieve their // collateral, regardless of whether they repay early. uint256 maximumRepaymentAmount; // The ID within the NFTCollateralContract for the NFT being used as // collateral for this loan. The NFT is stored within this contract // during the duration of the loan. uint256 nftCollateralId; // The block.timestamp when the loan first began (measured in seconds). uint64 loanStartTime; // The amount of time (measured in seconds) that can elapse before the // lender can liquidate the loan and seize the underlying collateral. uint32 loanDuration; // If interestIsProRated is set to true, then this is the interest rate // (measured in basis points, e.g. hundreths of a percent) for the loan, // that must be repaid pro-rata by the borrower at the conclusion of // the loan or risk seizure of their nft collateral. Note that if // interestIsProRated is set to false, then this value is not used and // is irrelevant. uint32 loanInterestRateForDurationInBasisPoints; // The percent (measured in basis points) of the interest earned that // will be taken as a fee by the contract admins when the loan is // repaid. The fee is stored here to prevent an attack where the // contract admins could adjust the fee right before a loan is repaid, // and take all of the interest earned. uint32 loanAdminFeeInBasisPoints; // The ERC721 contract of the NFT collateral address nftCollateralContract; // The ERC20 contract of the currency being used as principal/interest // for this loan. address loanERC20Denomination; // The address of the borrower. address borrower; // A boolean value determining whether the interest will be pro-rated // if the loan is repaid early, or whether the borrower will simply // pay maximumRepaymentAmount. bool interestIsProRated; } /* ****** */ /* EVENTS */ /* ****** */ // @notice This event is fired whenever a borrower begins a loan by calling // NFTfi.beginLoan(), which can only occur after both the lender // and borrower have approved their ERC721 and ERC20 contracts to // use NFTfi, and when they both have signed off-chain messages that // agree on the terms of the loan. // @param loanId - A unique identifier for this particular loan, sourced // from the continuously increasing parameter totalNumLoans. // @param borrower - The address of the borrower. // @param lender - The address of the lender. The lender can change their // address by transferring the NFTfi ERC721 token that they // received when the loan began. // @param loanPrincipalAmount - The original sum of money transferred from // lender to borrower at the beginning of the loan, measured in // loanERC20Denomination's smallest units. // @param maximumRepaymentAmount - The maximum amount of money that the // borrower would be required to retrieve their collateral. If // interestIsProRated is set to false, then the borrower will // always have to pay this amount to retrieve their collateral. // @param nftCollateralId - The ID within the NFTCollateralContract for the // NFT being used as collateral for this loan. The NFT is stored // within this contract during the duration of the loan. // @param loanStartTime - The block.timestamp when the loan first began // (measured in seconds). // @param loanDuration - The amount of time (measured in seconds) that can // elapse before the lender can liquidate the loan and seize the // underlying collateral NFT. // @param loanInterestRateForDurationInBasisPoints - If interestIsProRated // is set to true, then this is the interest rate (measured in // basis points, e.g. hundreths of a percent) for the loan, that // must be repaid pro-rata by the borrower at the conclusion of the // loan or risk seizure of their nft collateral. Note that if // interestIsProRated is set to false, then this value is not used // and is irrelevant. // @param nftCollateralContract - The ERC721 contract of the NFT collateral // @param loanERC20Denomination - The ERC20 contract of the currency being // used as principal/interest for this loan. // @param interestIsProRated - A boolean value determining whether the // interest will be pro-rated if the loan is repaid early, or // whether the borrower will simply pay maximumRepaymentAmount. event LoanStarted( uint256 loanId, address borrower, address lender, uint256 loanPrincipalAmount, uint256 maximumRepaymentAmount, uint256 nftCollateralId, uint256 loanStartTime, uint256 loanDuration, uint256 loanInterestRateForDurationInBasisPoints, address nftCollateralContract, address loanERC20Denomination, bool interestIsProRated ); // @notice This event is fired whenever a borrower successfully repays // their loan, paying principal-plus-interest-minus-fee to the // lender in loanERC20Denomination, paying fee to owner in // loanERC20Denomination, and receiving their NFT collateral back. // @param loanId - A unique identifier for this particular loan, sourced // from the continuously increasing parameter totalNumLoans. // @param borrower - The address of the borrower. // @param lender - The address of the lender. The lender can change their // address by transferring the NFTfi ERC721 token that they // received when the loan began. // @param loanPrincipalAmount - The original sum of money transferred from // lender to borrower at the beginning of the loan, measured in // loanERC20Denomination's smallest units. // @param nftCollateralId - The ID within the NFTCollateralContract for the // NFT being used as collateral for this loan. The NFT is stored // within this contract during the duration of the loan. // @param amountPaidToLender The amount of ERC20 that the borrower paid to // the lender, measured in the smalled units of // loanERC20Denomination. // @param adminFee The amount of interest paid to the contract admins, // measured in the smalled units of loanERC20Denomination and // determined by adminFeeInBasisPoints. This amount never exceeds // the amount of interest earned. // @param nftCollateralContract - The ERC721 contract of the NFT collateral // @param loanERC20Denomination - The ERC20 contract of the currency being // used as principal/interest for this loan. event LoanRepaid( uint256 loanId, address borrower, address lender, uint256 loanPrincipalAmount, uint256 nftCollateralId, uint256 amountPaidToLender, uint256 adminFee, address nftCollateralContract, address loanERC20Denomination ); // @notice This event is fired whenever a lender liquidates an outstanding // loan that is owned to them that has exceeded its duration. The // lender receives the underlying NFT collateral, and the borrower // no longer needs to repay the loan principal-plus-interest. // @param loanId - A unique identifier for this particular loan, sourced // from the continuously increasing parameter totalNumLoans. // @param borrower - The address of the borrower. // @param lender - The address of the lender. The lender can change their // address by transferring the NFTfi ERC721 token that they // received when the loan began. // @param loanPrincipalAmount - The original sum of money transferred from // lender to borrower at the beginning of the loan, measured in // loanERC20Denomination's smallest units. // @param nftCollateralId - The ID within the NFTCollateralContract for the // NFT being used as collateral for this loan. The NFT is stored // within this contract during the duration of the loan. // @param loanMaturityDate - The unix time (measured in seconds) that the // loan became due and was eligible for liquidation. // @param loanLiquidationDate - The unix time (measured in seconds) that // liquidation occurred. // @param nftCollateralContract - The ERC721 contract of the NFT collateral event LoanLiquidated( uint256 loanId, address borrower, address lender, uint256 loanPrincipalAmount, uint256 nftCollateralId, uint256 loanMaturityDate, uint256 loanLiquidationDate, address nftCollateralContract ); /* ******* */ /* STORAGE */ /* ******* */ // @notice A continuously increasing counter that simultaneously allows // every loan to have a unique ID and provides a running count of // how many loans have been started by this contract. uint256 public totalNumLoans = 0; // @notice A counter of the number of currently outstanding loans. uint256 public totalActiveLoans = 0; // @notice A mapping from a loan's identifier to the loan's details, // represted by the loan struct. To fetch the lender, call // NFTfi.ownerOf(loanId). mapping (uint256 => Loan) public loanIdToLoan; // @notice A mapping tracking whether a loan has either been repaid or // liquidated. This prevents an attacker trying to repay or // liquidate the same loan twice. mapping (uint256 => bool) public loanRepaidOrLiquidated; // @notice A mapping that takes both a user's address and a loan nonce // that was first used when signing an off-chain order and checks // whether that nonce has previously either been used for a loan, // or has been pre-emptively cancelled. The nonce referred to here // is not the same as an Ethereum account's nonce. We are referring // instead to nonces that are used by both the lender and the // borrower when they are first signing off-chain NFTfi orders. // These nonces can be any uint256 value that the user has not // previously used to sign an off-chain order. Each nonce can be // used at most once per user within NFTfi, regardless of whether // they are the lender or the borrower in that situation. This // serves two purposes. First, it prevents replay attacks where an // attacker would submit a user's off-chain order more than once. // Second, it allows a user to cancel an off-chain order by calling // NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the // nonce as used and prevents any future loan from using the user's // off-chain order that contains that nonce. mapping (address => mapping (uint256 => bool)) private _nonceHasBeenUsedForUser; /* *********** */ /* CONSTRUCTOR */ /* *********** */ constructor() public {} /* ********* */ /* FUNCTIONS */ /* ********* */ // @notice This function is called by a borrower when they want to commence // a loan, but can only be called after first: (1) the borrower has // called approve() or approveAll() on the NFT contract for the NFT // that will be used as collateral, (2) the borrower has signed an // off-chain message indicating that they are willing to use this // NFT as collateral, (3) the lender has called approve() on the // ERC20 contract of the principal, and (4) the lender has signed // an off-chain message agreeing to the terms of this loan supplied // in this transaction. // @notice Note that a user may submit UINT32_MAX as the value for // _loanInterestRateForDurationInBasisPoints to indicate that they // wish to take out a fixed-repayment loan, where the interest is // not pro-rated if repaid early. // @param _loanPrincipalAmount - The original sum of money transferred // from lender to borrower at the beginning of the loan, measured // in loanERC20Denomination's smallest units. // @param _maximumRepaymentAmount - The maximum amount of money that the // borrower would be required to retrieve their collateral, // measured in the smallest units of the ERC20 currency used for // the loan. If interestIsProRated is set to false (by submitting // a value of UINT32_MAX for // _loanInterestRateForDurationInBasisPoints), then the borrower // will always have to pay this amount to retrieve their // collateral, regardless of whether they repay early. // @param _nftCollateralId - The ID within the NFTCollateralContract for // the NFT being used as collateral for this loan. The NFT is // stored within this contract during the duration of the loan. // @param _loanDuration - The amount of time (measured in seconds) that can // elapse before the lender can liquidate the loan and seize the // underlying collateral NFT. // @param _loanInterestRateForDurationInBasisPoints - The interest rate // (measured in basis points, e.g. hundreths of a percent) for the // loan, that must be repaid pro-rata by the borrower at the // conclusion of the loan or risk seizure of their nft collateral. // However, a user may submit UINT32_MAX as the value for // _loanInterestRateForDurationInBasisPoints to indicate that they // wish to take out a fixed-repayment loan, where the interest is // not pro-rated if repaid early. Instead, maximumRepaymentAmount // will always be the amount to be repaid. // @param _adminFeeInBasisPoints - The percent (measured in basis // points) of the interest earned that will be taken as a fee by // the contract admins when the loan is repaid. The fee is stored // in the loan struct to prevent an attack where the contract // admins could adjust the fee right before a loan is repaid, and // take all of the interest earned. // @param _borrowerAndLenderNonces - An array of two UINT256 values, the // first of which is the _borrowerNonce and the second of which is // the _lenderNonce. The nonces referred to here are not the same // as an Ethereum account's nonce. We are referring instead to // nonces that are used by both the lender and the borrower when // they are first signing off-chain NFTfi orders. These nonces can // be any uint256 value that the user has not previously used to // sign an off-chain order. Each nonce can be used at most once per // user within NFTfi, regardless of whether they are the lender or // the borrower in that situation. This serves two purposes. First, // it prevents replay attacks where an attacker would submit a // user's off-chain order more than once. Second, it allows a user // to cancel an off-chain order by calling // NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the // nonce as used and prevents any future loan from using the user's // off-chain order that contains that nonce. // @param _nftCollateralContract - The address of the ERC721 contract of // the NFT collateral. // @param _loanERC20Denomination - The address of the ERC20 contract of // the currency being used as principal/interest for this loan. // @param _lender - The address of the lender. The lender can change their // address by transferring the NFTfi ERC721 token that they // received when the loan began. // @param _borrowerSignature - The ECDSA signature of the borrower, // obtained off-chain ahead of time, signing the following // combination of parameters: _nftCollateralId, _borrowerNonce, // _nftCollateralContract, _borrower. // @param _lenderSignature - The ECDSA signature of the lender, // obtained off-chain ahead of time, signing the following // combination of parameters: _loanPrincipalAmount, // _maximumRepaymentAmount _nftCollateralId, _loanDuration, // _loanInterestRateForDurationInBasisPoints, _lenderNonce, // _nftCollateralContract, _loanERC20Denomination, _lender, // _interestIsProRated. function beginLoan( uint256 _loanPrincipalAmount, uint256 _maximumRepaymentAmount, uint256 _nftCollateralId, uint256 _loanDuration, uint256 _loanInterestRateForDurationInBasisPoints, uint256 _adminFeeInBasisPoints, uint256[2] memory _borrowerAndLenderNonces, address _nftCollateralContract, address _loanERC20Denomination, address _lender, bytes memory _borrowerSignature, bytes memory _lenderSignature ) public whenNotPaused nonReentrant { // Save loan details to a struct in memory first, to save on gas if any // of the below checks fail, and to avoid the "Stack Too Deep" error by // clumping the parameters together into one struct held in memory. Loan memory loan = Loan({ loanId: totalNumLoans, //currentLoanId, loanPrincipalAmount: _loanPrincipalAmount, maximumRepaymentAmount: _maximumRepaymentAmount, nftCollateralId: _nftCollateralId, loanStartTime: uint64(now), //_loanStartTime loanDuration: uint32(_loanDuration), loanInterestRateForDurationInBasisPoints: uint32(_loanInterestRateForDurationInBasisPoints), loanAdminFeeInBasisPoints: uint32(_adminFeeInBasisPoints), nftCollateralContract: _nftCollateralContract, loanERC20Denomination: _loanERC20Denomination, borrower: msg.sender, //borrower interestIsProRated: (_loanInterestRateForDurationInBasisPoints != ~(uint32(0))) }); // Sanity check loan values. require(loan.maximumRepaymentAmount >= loan.loanPrincipalAmount, 'Negative interest rate loans are not allowed.'); require(uint256(loan.loanDuration) <= maximumLoanDuration, 'Loan duration exceeds maximum loan duration'); require(uint256(loan.loanDuration) != 0, 'Loan duration cannot be zero'); require(uint256(loan.loanAdminFeeInBasisPoints) == adminFeeInBasisPoints, 'The admin fee has changed since this order was signed.'); // Check that both the collateral and the principal come from supported // contracts. require(erc20CurrencyIsWhitelisted[loan.loanERC20Denomination], 'Currency denomination is not whitelisted to be used by this contract'); require(nftContractIsWhitelisted[loan.nftCollateralContract], 'NFT collateral contract is not whitelisted to be used by this contract'); // Check loan nonces. These are different from Ethereum account nonces. // Here, these are uint256 numbers that should uniquely identify // each signature for each user (i.e. each user should only create one // off-chain signature for each nonce, with a nonce being any arbitrary // uint256 value that they have not used yet for an off-chain NFTfi // signature). require(!_nonceHasBeenUsedForUser[msg.sender][_borrowerAndLenderNonces[0]], 'Borrower nonce invalid, borrower has either cancelled/begun this loan, or reused this nonce when signing'); _nonceHasBeenUsedForUser[msg.sender][_borrowerAndLenderNonces[0]] = true; require(!_nonceHasBeenUsedForUser[_lender][_borrowerAndLenderNonces[1]], 'Lender nonce invalid, lender has either cancelled/begun this loan, or reused this nonce when signing'); _nonceHasBeenUsedForUser[_lender][_borrowerAndLenderNonces[1]] = true; // Check that both signatures are valid. require(isValidBorrowerSignature( loan.nftCollateralId, _borrowerAndLenderNonces[0],//_borrowerNonce, loan.nftCollateralContract, msg.sender, //borrower, _borrowerSignature ), 'Borrower signature is invalid'); require(isValidLenderSignature( loan.loanPrincipalAmount, loan.maximumRepaymentAmount, loan.nftCollateralId, loan.loanDuration, loan.loanInterestRateForDurationInBasisPoints, loan.loanAdminFeeInBasisPoints, _borrowerAndLenderNonces[1],//_lenderNonce, loan.nftCollateralContract, loan.loanERC20Denomination, _lender, loan.interestIsProRated, _lenderSignature ), 'Lender signature is invalid'); // Add the loan to storage before moving collateral/principal to follow // the Checks-Effects-Interactions pattern. loanIdToLoan[totalNumLoans] = loan; totalNumLoans = totalNumLoans.add(1); // Update number of active loans. totalActiveLoans = totalActiveLoans.add(1); require(totalActiveLoans <= maximumNumberOfActiveLoans, 'Contract has reached the maximum number of active loans allowed by admins'); // Transfer collateral from borrower to this contract to be held until // loan completion. IERC721(loan.nftCollateralContract).transferFrom(msg.sender, address(this), loan.nftCollateralId); // Transfer principal from lender to borrower. IERC20(loan.loanERC20Denomination).transferFrom(_lender, msg.sender, loan.loanPrincipalAmount); // Issue an ERC721 promissory note to the lender that gives them the // right to either the principal-plus-interest or the collateral. _mint(_lender, loan.loanId); // Emit an event with all relevant details from this transaction. emit LoanStarted( loan.loanId, msg.sender, //borrower, _lender, loan.loanPrincipalAmount, loan.maximumRepaymentAmount, loan.nftCollateralId, now, //_loanStartTime loan.loanDuration, loan.loanInterestRateForDurationInBasisPoints, loan.nftCollateralContract, loan.loanERC20Denomination, loan.interestIsProRated ); } // @notice This function is called by a borrower when they want to repay // their loan. It can be called at any time after the loan has // begun. The borrower will pay a pro-rata portion of their // interest if the loan is paid off early. The interest will // continue to accrue after the loan has expired. This function can // continue to be called by the borrower even after the loan has // expired to retrieve their NFT. Note that the lender can call // NFTfi.liquidateOverdueLoan() at any time after the loan has // expired, so a borrower should avoid paying their loan after the // due date, as they risk their collateral being seized. However, // if a lender has called NFTfi.liquidateOverdueLoan() before a // borrower could call NFTfi.payBackLoan(), the borrower will get // to keep the principal-plus-interest. // @notice This function is purposefully not pausable in order to prevent // an attack where the contract admin's pause the contract and hold // hostage the NFT's that are still within it. // @param _loanId A unique identifier for this particular loan, sourced // from the continuously increasing parameter totalNumLoans. function payBackLoan(uint256 _loanId) external nonReentrant { // Sanity check that payBackLoan() and liquidateOverdueLoan() have // never been called on this loanId. Depending on how the rest of the // code turns out, this check may be unnecessary. require(!loanRepaidOrLiquidated[_loanId], 'Loan has already been repaid or liquidated'); // Fetch loan details from storage, but store them in memory for the // sake of saving gas. Loan memory loan = loanIdToLoan[_loanId]; // Check that the borrower is the caller, only the borrower is entitled // to the collateral. require(msg.sender == loan.borrower, 'Only the borrower can pay back a loan and reclaim the underlying NFT'); // Fetch current owner of loan promissory note. address lender = ownerOf(_loanId); // Calculate amounts to send to lender and admins uint256 interestDue = (loan.maximumRepaymentAmount).sub(loan.loanPrincipalAmount); if(loan.interestIsProRated == true){ interestDue = _computeInterestDue( loan.loanPrincipalAmount, loan.maximumRepaymentAmount, now.sub(uint256(loan.loanStartTime)), uint256(loan.loanDuration), uint256(loan.loanInterestRateForDurationInBasisPoints) ); } uint256 adminFee = _computeAdminFee(interestDue, uint256(loan.loanAdminFeeInBasisPoints)); uint256 payoffAmount = ((loan.loanPrincipalAmount).add(interestDue)).sub(adminFee); // Mark loan as repaid before doing any external transfers to follow // the Checks-Effects-Interactions design pattern. loanRepaidOrLiquidated[_loanId] = true; // Update number of active loans. totalActiveLoans = totalActiveLoans.sub(1); // Transfer principal-plus-interest-minus-fees from borrower to lender IERC20(loan.loanERC20Denomination).transferFrom(loan.borrower, lender, payoffAmount); // Transfer fees from borrower to admins IERC20(loan.loanERC20Denomination).transferFrom(loan.borrower, owner(), adminFee); // Transfer collateral from this contract to borrower. require(_transferNftToAddress( loan.nftCollateralContract, loan.nftCollateralId, loan.borrower ), 'NFT was not successfully transferred'); // Destroy the lender's promissory note. _burn(_loanId); // Emit an event with all relevant details from this transaction. emit LoanRepaid( _loanId, loan.borrower, lender, loan.loanPrincipalAmount, loan.nftCollateralId, payoffAmount, adminFee, loan.nftCollateralContract, loan.loanERC20Denomination ); // Delete the loan from storage in order to achieve a substantial gas // savings and to lessen the burden of storage on Ethereum nodes, since // we will never access this loan's details again, and the details are // still available through event data. delete loanIdToLoan[_loanId]; } // @notice This function is called by a lender once a loan has finished its // duration and the borrower still has not repaid. The lender // can call this function to seize the underlying NFT collateral, // although the lender gives up all rights to the // principal-plus-collateral by doing so. // @notice This function is purposefully not pausable in order to prevent // an attack where the contract admin's pause the contract and hold // hostage the NFT's that are still within it. // @notice We intentionally allow anybody to call this function, although // only the lender will end up receiving the seized collateral. We // are exploring the possbility of incentivizing users to call this // function by using some of the admin funds. // @param _loanId A unique identifier for this particular loan, sourced // from the continuously increasing parameter totalNumLoans. function liquidateOverdueLoan(uint256 _loanId) external nonReentrant { // Sanity check that payBackLoan() and liquidateOverdueLoan() have // never been called on this loanId. Depending on how the rest of the // code turns out, this check may be unnecessary. require(!loanRepaidOrLiquidated[_loanId], 'Loan has already been repaid or liquidated'); // Fetch loan details from storage, but store them in memory for the // sake of saving gas. Loan memory loan = loanIdToLoan[_loanId]; // Ensure that the loan is indeed overdue, since we can only liquidate // overdue loans. uint256 loanMaturityDate = (uint256(loan.loanStartTime)).add(uint256(loan.loanDuration)); require(now > loanMaturityDate, 'Loan is not overdue yet'); // Fetch the current lender of the promissory note corresponding to // this overdue loan. address lender = ownerOf(_loanId); // Mark loan as liquidated before doing any external transfers to // follow the Checks-Effects-Interactions design pattern. loanRepaidOrLiquidated[_loanId] = true; // Update number of active loans. totalActiveLoans = totalActiveLoans.sub(1); // Transfer collateral from this contract to the lender, since the // lender is seizing collateral for an overdue loan. require(_transferNftToAddress( loan.nftCollateralContract, loan.nftCollateralId, lender ), 'NFT was not successfully transferred'); // Destroy the lender's promissory note for this loan, since by seizing // the collateral, the lender has forfeit the rights to the loan // principal-plus-interest. _burn(_loanId); // Emit an event with all relevant details from this transaction. emit LoanLiquidated( _loanId, loan.borrower, lender, loan.loanPrincipalAmount, loan.nftCollateralId, loanMaturityDate, now, loan.nftCollateralContract ); // Delete the loan from storage in order to achieve a substantial gas // savings and to lessen the burden of storage on Ethereum nodes, since // we will never access this loan's details again, and the details are // still available through event data. delete loanIdToLoan[_loanId]; } // @notice This function can be called by either a lender or a borrower to // cancel all off-chain orders that they have signed that contain // this nonce. If the off-chain orders were created correctly, // there should only be one off-chain order that contains this // nonce at all. // @param _nonce - The nonce referred to here is not the same as an // Ethereum account's nonce. We are referring instead to nonces // that are used by both the lender and the borrower when they are // first signing off-chain NFTfi orders. These nonces can be any // uint256 value that the user has not previously used to sign an // off-chain order. Each nonce can be used at most once per user // within NFTfi, regardless of whether they are the lender or the // borrower in that situation. This serves two purposes. First, it // prevents replay attacks where an attacker would submit a user's // off-chain order more than once. Second, it allows a user to // cancel an off-chain order by calling // NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the // nonce as used and prevents any future loan from using the user's // off-chain order that contains that nonce. function cancelLoanCommitmentBeforeLoanHasBegun(uint256 _nonce) external { require(!_nonceHasBeenUsedForUser[msg.sender][_nonce], 'Nonce invalid, user has either cancelled/begun this loan, or reused a nonce when signing'); _nonceHasBeenUsedForUser[msg.sender][_nonce] = true; } /* ******************* */ /* READ-ONLY FUNCTIONS */ /* ******************* */ // @notice This function can be used to view the current quantity of the // ERC20 currency used in the specified loan required by the // borrower to repay their loan, measured in the smallest unit of // the ERC20 currency. Note that since interest accrues every // second, once a borrower calls repayLoan(), the amount will have // increased slightly. // @param _loanId A unique identifier for this particular loan, sourced // from the continuously increasing parameter totalNumLoans. // @return The amount of the specified ERC20 currency required to pay back // this loan, measured in the smallest unit of the specified ERC20 // currency. function getPayoffAmount(uint256 _loanId) public view returns (uint256) { Loan storage loan = loanIdToLoan[_loanId]; if(loan.interestIsProRated == false){ return loan.maximumRepaymentAmount; } else { uint256 loanDurationSoFarInSeconds = now.sub(uint256(loan.loanStartTime)); uint256 interestDue = _computeInterestDue(loan.loanPrincipalAmount, loan.maximumRepaymentAmount, loanDurationSoFarInSeconds, uint256(loan.loanDuration), uint256(loan.loanInterestRateForDurationInBasisPoints)); return (loan.loanPrincipalAmount).add(interestDue); } } // @notice This function can be used to view whether a particular nonce // for a particular user has already been used, either from a // successful loan or a cancelled off-chain order. // @param _user - The address of the user. This function works for both // lenders and borrowers alike. // @param _nonce - The nonce referred to here is not the same as an // Ethereum account's nonce. We are referring instead to nonces // that are used by both the lender and the borrower when they are // first signing off-chain NFTfi orders. These nonces can be any // uint256 value that the user has not previously used to sign an // off-chain order. Each nonce can be used at most once per user // within NFTfi, regardless of whether they are the lender or the // borrower in that situation. This serves two purposes. First, it // prevents replay attacks where an attacker would submit a user's // off-chain order more than once. Second, it allows a user to // cancel an off-chain order by calling // NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the // nonce as used and prevents any future loan from using the user's // off-chain order that contains that nonce. // @return A bool representing whether or not this nonce has been used for // this user. function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) public view returns (bool) { return _nonceHasBeenUsedForUser[_user][_nonce]; } /* ****************** */ /* INTERNAL FUNCTIONS */ /* ****************** */ // @notice A convenience function that calculates the amount of interest // currently due for a given loan. The interest is capped at // _maximumRepaymentAmount minus _loanPrincipalAmount. // @param _loanPrincipalAmount - The total quantity of principal first // loaned to the borrower, measured in the smallest units of the // ERC20 currency used for the loan. // @param _maximumRepaymentAmount - The maximum amount of money that the // borrower would be required to retrieve their collateral. If // interestIsProRated is set to false, then the borrower will // always have to pay this amount to retrieve their collateral. // @param _loanDurationSoFarInSeconds - The elapsed time (in seconds) that // has occurred so far since the loan began until repayment. // @param _loanTotalDurationAgreedTo - The original duration that the // borrower and lender agreed to, by which they measured the // interest that would be due. // @param _loanInterestRateForDurationInBasisPoints - The interest rate /// that the borrower and lender agreed would be due after the // totalDuration passed. // @return The quantity of interest due, measured in the smallest units of // the ERC20 currency used to pay this loan. function _computeInterestDue(uint256 _loanPrincipalAmount, uint256 _maximumRepaymentAmount, uint256 _loanDurationSoFarInSeconds, uint256 _loanTotalDurationAgreedTo, uint256 _loanInterestRateForDurationInBasisPoints) internal pure returns (uint256) { uint256 interestDueAfterEntireDuration = (_loanPrincipalAmount.mul(_loanInterestRateForDurationInBasisPoints)).div(uint256(10000)); uint256 interestDueAfterElapsedDuration = (interestDueAfterEntireDuration.mul(_loanDurationSoFarInSeconds)).div(_loanTotalDurationAgreedTo); if(_loanPrincipalAmount.add(interestDueAfterElapsedDuration) > _maximumRepaymentAmount){ return _maximumRepaymentAmount.sub(_loanPrincipalAmount); } else { return interestDueAfterElapsedDuration; } } // @notice A convenience function computing the adminFee taken from a // specified quantity of interest // @param _interestDue - The amount of interest due, measured in the // smallest quantity of the ERC20 currency being used to pay the // interest. // @param _adminFeeInBasisPoints - The percent (measured in basis // points) of the interest earned that will be taken as a fee by // the contract admins when the loan is repaid. The fee is stored // in the loan struct to prevent an attack where the contract // admins could adjust the fee right before a loan is repaid, and // take all of the interest earned. // @return The quantity of ERC20 currency (measured in smalled units of // that ERC20 currency) that is due as an admin fee. function _computeAdminFee(uint256 _interestDue, uint256 _adminFeeInBasisPoints) internal pure returns (uint256) { return (_interestDue.mul(_adminFeeInBasisPoints)).div(10000); } // @notice We call this function when we wish to transfer an NFT from our // contract to another destination. Since some prominent NFT // contracts do not conform to the same standard, we try multiple // variations on transfer/transferFrom, and check whether any // succeeded. // @notice Some nft contracts will not allow you to approve your own // address or do not allow you to call transferFrom() when you are // the sender, (for example, CryptoKitties does not allow you to), // while other nft contracts do not implement transfer() (since it // is not part of the official ERC721 standard but is implemented // in some prominent nft projects such as Cryptokitties), so we // must try calling transferFrom() and transfer(), and see if one // succeeds. // @param _nftContract - The NFT contract that we are attempting to // transfer an NFT from. // @param _nftId - The ID of the NFT that we are attempting to transfer. // @param _recipient - The destination of the NFT that we are attempting // to transfer. // @return A bool value indicating whether the transfer attempt succeeded. function _transferNftToAddress(address _nftContract, uint256 _nftId, address _recipient) internal returns (bool) { // Try to call transferFrom() bool transferFromSucceeded = _attemptTransferFrom(_nftContract, _nftId, _recipient); if(transferFromSucceeded){ return true; } else { // Try to call transfer() bool transferSucceeded = _attemptTransfer(_nftContract, _nftId, _recipient); return transferSucceeded; } } // @notice This function attempts to call transferFrom() on the specified // NFT contract, returning whether it succeeded. // @notice We only call this function from within _transferNftToAddress(), // which is function attempts to call the various ways that // different NFT contracts have implemented transfer/transferFrom. // @param _nftContract - The NFT contract that we are attempting to // transfer an NFT from. // @param _nftId - The ID of the NFT that we are attempting to transfer. // @param _recipient - The destination of the NFT that we are attempting // to transfer. // @return A bool value indicating whether the transfer attempt succeeded. function _attemptTransferFrom(address _nftContract, uint256 _nftId, address _recipient) internal returns (bool) { // @notice Some NFT contracts will not allow you to approve an NFT that // you own, so we cannot simply call approve() here, we have to // try to call it in a manner that allows the call to fail. _nftContract.call(abi.encodeWithSelector(IERC721(_nftContract).approve.selector, address(this), _nftId)); // @notice Some NFT contracts will not allow you to call transferFrom() // for an NFT that you own but that is not approved, so we // cannot simply call transferFrom() here, we have to try to // call it in a manner that allows the call to fail. (bool success, ) = _nftContract.call(abi.encodeWithSelector(IERC721(_nftContract).transferFrom.selector, address(this), _recipient, _nftId)); return success; } // @notice This function attempts to call transfer() on the specified // NFT contract, returning whether it succeeded. // @notice We only call this function from within _transferNftToAddress(), // which is function attempts to call the various ways that // different NFT contracts have implemented transfer/transferFrom. // @param _nftContract - The NFT contract that we are attempting to // transfer an NFT from. // @param _nftId - The ID of the NFT that we are attempting to transfer. // @param _recipient - The destination of the NFT that we are attempting // to transfer. // @return A bool value indicating whether the transfer attempt succeeded. function _attemptTransfer(address _nftContract, uint256 _nftId, address _recipient) internal returns (bool) { // @notice Some NFT contracts do not implement transfer(), since it is // not a part of the official ERC721 standard, but many // prominent NFT projects do implement it (such as // Cryptokitties), so we cannot simply call transfer() here, we // have to try to call it in a manner that allows the call to // fail. (bool success, ) = _nftContract.call(abi.encodeWithSelector(ICryptoKittiesCore(_nftContract).transfer.selector, _recipient, _nftId)); return success; } /* ***************** */ /* FALLBACK FUNCTION */ /* ***************** */ // @notice By calling 'revert' in the fallback function, we prevent anyone // from accidentally sending funds directly to this contract. function() external payable { revert(); } } // @notice The interface for interacting with the CryptoKitties contract. We // include this special case because CryptoKitties is one of the most // used NFT contracts on Ethereum and will likely be used by NFTfi, but // it does not perfectly abide by the ERC721 standard, since it preceded // the official standardization of ERC721. contract ICryptoKittiesCore { function transfer(address _to, uint256 _tokenId) external; }
@notice We call this function when we wish to transfer an NFT from our contract to another destination. Since some prominent NFT contracts do not conform to the same standard, we try multiple variations on transfer/transferFrom, and check whether any succeeded. @notice Some nft contracts will not allow you to approve your own address or do not allow you to call transferFrom() when you are the sender, (for example, CryptoKitties does not allow you to), while other nft contracts do not implement transfer() (since it is not part of the official ERC721 standard but is implemented in some prominent nft projects such as Cryptokitties), so we must try calling transferFrom() and transfer(), and see if one succeeds. @param _nftContract - The NFT contract that we are attempting to transfer an NFT from. @param _nftId - The ID of the NFT that we are attempting to transfer. @param _recipient - The destination of the NFT that we are attempting to transfer. @return A bool value indicating whether the transfer attempt succeeded. Try to call transferFrom() Try to call transfer()
function _transferNftToAddress(address _nftContract, uint256 _nftId, address _recipient) internal returns (bool) { bool transferFromSucceeded = _attemptTransferFrom(_nftContract, _nftId, _recipient); if(transferFromSucceeded){ return true; bool transferSucceeded = _attemptTransfer(_nftContract, _nftId, _recipient); return transferSucceeded; } }
12,852,756
[ 1, 3218, 745, 333, 445, 1347, 732, 14302, 358, 7412, 392, 423, 4464, 628, 3134, 540, 6835, 358, 4042, 2929, 18, 7897, 2690, 450, 1154, 319, 423, 4464, 540, 20092, 741, 486, 20156, 358, 326, 1967, 4529, 16, 732, 775, 3229, 540, 28401, 603, 7412, 19, 13866, 1265, 16, 471, 866, 2856, 1281, 540, 15784, 18, 225, 10548, 290, 1222, 20092, 903, 486, 1699, 1846, 358, 6617, 537, 3433, 4953, 540, 1758, 578, 741, 486, 1699, 1846, 358, 745, 7412, 1265, 1435, 1347, 1846, 854, 540, 326, 5793, 16, 261, 1884, 3454, 16, 15629, 14102, 88, 606, 1552, 486, 1699, 1846, 358, 3631, 540, 1323, 1308, 290, 1222, 20092, 741, 486, 2348, 7412, 1435, 261, 9256, 518, 540, 353, 486, 1087, 434, 326, 3397, 22354, 4232, 39, 27, 5340, 4529, 1496, 353, 8249, 540, 316, 2690, 450, 1154, 319, 290, 1222, 10137, 4123, 487, 22752, 601, 305, 88, 606, 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, 389, 13866, 50, 1222, 774, 1887, 12, 2867, 389, 82, 1222, 8924, 16, 2254, 5034, 389, 82, 1222, 548, 16, 1758, 389, 20367, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 1426, 7412, 1265, 30500, 273, 389, 11764, 5912, 1265, 24899, 82, 1222, 8924, 16, 389, 82, 1222, 548, 16, 389, 20367, 1769, 203, 3639, 309, 12, 13866, 1265, 30500, 15329, 203, 5411, 327, 638, 31, 203, 5411, 1426, 7412, 30500, 273, 389, 11764, 5912, 24899, 82, 1222, 8924, 16, 389, 82, 1222, 548, 16, 389, 20367, 1769, 203, 5411, 327, 7412, 30500, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.6; import {ERC721} from '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import {IMetaDataGenerator} from './interfaces/IMetaDataGenerator.sol'; import {ICryptoPiggies} from './interfaces/ICryptoPiggies.sol'; /** * @dev Implementation of the Non-Fungible Token CryptoPiggies which uses a MetaDataGenerator to generate MetaData fully on-chain * Each piggy stores some eth, which can be redeemed by breaking the piggie, so there is a hard floor for sellers. */ contract CryptoPiggies is ERC721, ICryptoPiggies { address payable public override treasury; IMetaDataGenerator public immutable override METADATAGENERATOR; mapping(uint256 => Piggy) piggies; uint256 public constant MINT_MASK = 0xfffff; uint256 public constant MINT_PRICE = 0.1 ether; uint256 public constant MINT_VALUE = MINT_PRICE / 2; uint256 public constant FLIP_MIN_COST = 0.01 ether; uint256 public constant MAX_SUPPLY = 10000; uint256 public constant MAX_MINT = 20; uint256 internal _supply = 0; uint256 internal _broken = 0; constructor(address payable treasury_, IMetaDataGenerator generator) ERC721('CryptoPiggies', 'CPig') { treasury = treasury_; METADATAGENERATOR = generator; } function setTreasury(address payable treasury_) public { require(treasury == msg.sender, 'caller not treasury'); treasury = treasury_; } /** * @dev Mints CryptoPiggies to the msg.sender when receiving ETH directly. * Computes the number of CryptoPiggies from the msg.value */ receive() external payable override { uint256 piggiesToMint = msg.value / MINT_PRICE; giftPiggies(piggiesToMint > MAX_MINT ? MAX_MINT : piggiesToMint, msg.sender); } /** * @dev Mints CryptoPiggies to the msg.sender * @param piggiesToMint the amount of CryptoPiggies to mint */ function mintPiggies(uint256 piggiesToMint) public payable override { giftPiggies(piggiesToMint, msg.sender); } /** * @dev Minting CryptoPiggies to another account than msg.sender * @param piggiesToMint the amount of CryptoPiggies to mint * @param to the address to receive those CryptoPiggies */ function giftPiggies(uint256 piggiesToMint, address to) public payable override { uint256 supply = _supply; require(piggiesToMint > 0, 'cannot mint 0 piggies'); require(piggiesToMint <= MAX_MINT, 'exceeds max mint'); require(supply + piggiesToMint <= MAX_SUPPLY, 'exceeds max supply'); require(msg.value >= MINT_PRICE * piggiesToMint, 'insufficient eth'); _supply = _supply + piggiesToMint; for (uint256 i = 0; i < piggiesToMint; i++) { _mintPiggie(to, supply + i); } treasury.transfer(MINT_VALUE * piggiesToMint); uint256 refundAmount = msg.value - piggiesToMint * MINT_PRICE; payable(msg.sender).transfer(refundAmount); } /** * @dev Destroy CryptoPiggies to redeem the ETH they hold * @param tokenIds the CryptoPiggies to destroy * @param to the receiver of the funds */ function breakPiggies(uint256[] memory tokenIds, address payable to) external override { uint256 fundsInBroken = 0; for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; fundsInBroken += _breakPiggie(tokenId); } _broken += tokenIds.length; to.transfer(fundsInBroken); emit Break(tokenIds.length, fundsInBroken, to); } /** * @dev Resets the trait mask to the initial mask * @param tokenId the CryptoPiggy to reset */ function resetTraitMask(uint256 tokenId) public override { require(_isApprovedOrOwner(msg.sender, tokenId), 'caller is not approved nor owner'); piggies[tokenId].traitMask = MINT_MASK; piggies[tokenId].flipCost = FLIP_MIN_COST; emit ResetMask(tokenId); } /** * @dev Update multiple traits at once * @param tokenId the CryptoPiggy to update traits on * @param positions the traits to flip * @param onOffs whether to turn the trait on or off */ function updateMultipleTraits( uint256 tokenId, uint256[] memory positions, bool[] memory onOffs ) public payable override { require(_isApprovedOrOwner(msg.sender, tokenId), 'caller is not approved nor owner'); require(positions.length == onOffs.length, 'length mismatch'); uint256 costOfFlipping = 0; for (uint256 i = 0; i < positions.length; i++) { costOfFlipping += piggies[tokenId].flipCost * (2**i); } require(msg.value >= costOfFlipping, 'insufficient eth'); Piggy memory piggie = piggies[tokenId]; for (uint256 i = 0; i < positions.length; i++) { require(positions[i] > 4, 'cannot flip piggy or colors'); if (onOffs[i]) { piggie.traitMask = newMask(piggie.traitMask, 15, positions[i]); emit TurnTraitOn(tokenId, positions[i]); } else { piggie.traitMask = newMask(piggie.traitMask, 0, positions[i]); emit TurnTraitOff(tokenId, positions[i]); } } piggie.flipCost = piggie.flipCost * (2 * (positions.length)); piggie.balance += msg.value / 2; piggies[tokenId] = piggie; treasury.transfer(msg.value / 2); } /** * @dev Turn on a nibble (4 bits) in the trait mask. * @param tokenId the CryptoPiggy to update mask for * @param position nibble index from the right to flip */ function turnTraitOn(uint256 tokenId, uint256 position) public payable override { require(_isApprovedOrOwner(msg.sender, tokenId), 'caller is not approved nor owner'); _updateTraitMask(tokenId, 15, position); emit TurnTraitOn(tokenId, position); } /** * @dev Turn off a nibble (4 bits) in the trait mask. * @param tokenId the CryptoPiggy to update mask for * @param position nibble index from the right to flip */ function turnTraitOff(uint256 tokenId, uint256 position) public payable override { require(_isApprovedOrOwner(msg.sender, tokenId), 'caller is not approved nor owner'); _updateTraitMask(tokenId, 0, position); emit TurnTraitOff(tokenId, position); } /** * @dev Donates ETH from msg.value directly to a CryptoPiggy * @param tokenId the CryptoPiggy to donate to */ function deposit(uint256 tokenId) public payable override { require(_exists(tokenId), 'cannot deposit to non-existing piggy'); piggies[tokenId].balance += msg.value; emit Deposit(tokenId, msg.value); } /** * @dev Generates SVG image for CryptoPiggy with the activeGene and balance * @param tokenId the CryptoPiggy to generate image for * @return SVG contents */ function getSVG(uint256 tokenId) public view override returns (string memory) { return METADATAGENERATOR.getSVG(activeGeneOf(tokenId), piggyBalance(tokenId)); } /** * @dev Generates MetaData for a specific CryptoPiggy using its activeGene and balance * @param tokenId the CryptoPiggy to generate metadata for * @return Base64 encoded MetaData for the CryptoPiggy */ function tokenURI(uint256 tokenId) public view override returns (string memory) { IMetaDataGenerator.MetaDataParams memory params = IMetaDataGenerator.MetaDataParams( tokenId, activeGeneOf(tokenId), piggyBalance(tokenId), ownerOf(tokenId) ); return METADATAGENERATOR.tokenURI(params); } function totalSupply() external view returns (uint256) { return _supply; } function broken() external view override returns (uint256) { return _broken; } function geneOf(uint256 tokenId) external view override returns (uint256) { return piggies[tokenId].gene; } function traitMaskOf(uint256 tokenId) external view override returns (uint256) { return piggies[tokenId].traitMask; } function activeGeneOf(uint256 tokenId) public view override returns (uint256) { return piggies[tokenId].gene & piggies[tokenId].traitMask; } function piggyBalance(uint256 tokenId) public view override returns (uint256) { return piggies[tokenId].balance; } function flipCost(uint256 tokenId) external view override returns (uint256) { return piggies[tokenId].flipCost; } function getPiggy(uint256 tokenId) external view override returns (Piggy memory) { return piggies[tokenId]; } // Internal functions function _mintPiggie(address to, uint256 tokenId) internal { // Semi gameable gene uint256 gene = uint256( keccak256( abi.encode( blockhash(block.number), // blockhash(block.number - 50), // This is why coverage is fuckeds gasleft(), msg.sender, to, tokenId, _supply, _broken ) ) ); piggies[tokenId] = Piggy(gene, MINT_MASK, MINT_VALUE, FLIP_MIN_COST); _mint(to, tokenId); } function _breakPiggie(uint256 tokenId) internal returns (uint256 balance) { require(_isApprovedOrOwner(_msgSender(), tokenId), 'caller is not approved nor owner'); balance = piggies[tokenId].balance; delete piggies[tokenId]; _burn(tokenId); } function _updateTraitMask( uint256 tokenId, uint256 replaceValue, uint256 position ) internal { require(position > 4, 'cannot flip piggy or colors'); Piggy memory piggie = piggies[tokenId]; require(msg.value >= piggie.flipCost, 'insufficient eth'); piggie.traitMask = newMask(piggie.traitMask, replaceValue, position); piggie.flipCost += piggie.flipCost; piggie.balance += msg.value / 2; piggies[tokenId] = piggie; treasury.transfer(msg.value / 2); } function newMask( uint256 mask, uint256 replacement, uint256 position ) internal pure virtual returns (uint256) { uint256 rhs = position > 0 ? mask % 16**position : 0; uint256 lhs = (mask / (16**(position + 1))) * (16**(position + 1)); uint256 insert = replacement * 16**position; return lhs + insert + rhs; } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.6; import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import {IMetaDataGenerator} from './IMetaDataGenerator.sol'; interface ICryptoPiggies is IERC721 { struct Piggy { uint256 gene; uint256 traitMask; uint256 balance; uint256 flipCost; } // Events event ResetMask(uint256 tokenId); event TurnTraitOn(uint256 tokenId, uint256 position); event TurnTraitOff(uint256 tokenId, uint256 position); event Deposit(uint256 tokenId, uint256 amount); event Break(uint256 piggiesBroken, uint256 amount, address to); // Functions for minting receive() external payable; function mintPiggies(uint256 piggiesToMint) external payable; function giftPiggies(uint256 piggiesToMint, address to) external payable; // Breaking function breakPiggies(uint256[] memory tokenIds, address payable to) external; // Manipulating mask function resetTraitMask(uint256 tokenId) external; function turnTraitOn(uint256 tokenId, uint256 position) external payable; function turnTraitOff(uint256 tokenId, uint256 position) external payable; function updateMultipleTraits( uint256 tokenId, uint256[] memory position, bool[] memory onOff ) external payable; // Depositing eth into a piggy function deposit(uint256 tokenId) external payable; // Views function getSVG(uint256 tokenId) external view returns (string memory); function piggyBalance(uint256 tokenId) external view returns (uint256); function geneOf(uint256 tokenId) external view returns (uint256); function traitMaskOf(uint256 tokenId) external view returns (uint256); function activeGeneOf(uint256 tokenId) external view returns (uint256); function getPiggy(uint256 tokenId) external view returns (Piggy memory); function flipCost(uint256 tokenId) external view returns (uint256); function broken() external view returns (uint256); function treasury() external view returns (address payable); function METADATAGENERATOR() external view returns (IMetaDataGenerator); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.6; interface IMetaDataGenerator { struct MetaDataParams { uint256 tokenId; uint256 activeGene; uint256 balance; address owner; } struct Attribute { uint256 layer; uint256 scene; } struct EncodedData { uint8[576] composite; uint256[] colorPalette; string[] attributes; } function getSVG(uint256 activeGene, uint256 balance) external view returns (string memory); function tokenURI(MetaDataParams memory params) external view returns (string memory); function getEncodedData(uint256 activeGene) external view returns (EncodedData memory); function ossified() external view returns (bool); }
* @dev Minting CryptoPiggies to another account than msg.sender @param piggiesToMint the amount of CryptoPiggies to mint @param to the address to receive those CryptoPiggies/
function giftPiggies(uint256 piggiesToMint, address to) public payable override { uint256 supply = _supply; require(piggiesToMint > 0, 'cannot mint 0 piggies'); require(piggiesToMint <= MAX_MINT, 'exceeds max mint'); require(supply + piggiesToMint <= MAX_SUPPLY, 'exceeds max supply'); require(msg.value >= MINT_PRICE * piggiesToMint, 'insufficient eth'); _supply = _supply + piggiesToMint; for (uint256 i = 0; i < piggiesToMint; i++) { _mintPiggie(to, supply + i); } treasury.transfer(MINT_VALUE * piggiesToMint); uint256 refundAmount = msg.value - piggiesToMint * MINT_PRICE; payable(msg.sender).transfer(refundAmount); }
6,874,778
[ 1, 49, 474, 310, 15629, 52, 360, 20921, 358, 4042, 2236, 2353, 1234, 18, 15330, 225, 293, 360, 20921, 774, 49, 474, 326, 3844, 434, 15629, 52, 360, 20921, 358, 312, 474, 225, 358, 326, 1758, 358, 6798, 5348, 15629, 52, 360, 20921, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 314, 2136, 52, 360, 20921, 12, 11890, 5034, 293, 360, 20921, 774, 49, 474, 16, 1758, 358, 13, 1071, 8843, 429, 3849, 288, 203, 3639, 2254, 5034, 14467, 273, 389, 2859, 1283, 31, 203, 3639, 2583, 12, 84, 360, 20921, 774, 49, 474, 405, 374, 16, 296, 12892, 312, 474, 374, 293, 360, 20921, 8284, 203, 3639, 2583, 12, 84, 360, 20921, 774, 49, 474, 1648, 4552, 67, 49, 3217, 16, 296, 338, 5288, 87, 943, 312, 474, 8284, 203, 3639, 2583, 12, 2859, 1283, 397, 293, 360, 20921, 774, 49, 474, 1648, 4552, 67, 13272, 23893, 16, 296, 338, 5288, 87, 943, 14467, 8284, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 490, 3217, 67, 7698, 1441, 380, 293, 360, 20921, 774, 49, 474, 16, 296, 2679, 11339, 13750, 8284, 203, 3639, 389, 2859, 1283, 273, 389, 2859, 1283, 397, 293, 360, 20921, 774, 49, 474, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 293, 360, 20921, 774, 49, 474, 31, 277, 27245, 288, 203, 5411, 389, 81, 474, 52, 360, 75, 1385, 12, 869, 16, 14467, 397, 277, 1769, 203, 3639, 289, 203, 3639, 9787, 345, 22498, 18, 13866, 12, 49, 3217, 67, 4051, 380, 293, 360, 20921, 774, 49, 474, 1769, 203, 3639, 2254, 5034, 16255, 6275, 273, 1234, 18, 1132, 300, 293, 360, 20921, 774, 49, 474, 380, 490, 3217, 67, 7698, 1441, 31, 203, 3639, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 1734, 1074, 6275, 1769, 203, 565, 289, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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; /** * @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 "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.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 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: ISC pragma solidity ^0.8.0 <0.9.0; /// @title IAuthenticator /// @dev Authenticator interface /// @author Frank Bonnet - <[email protected]> interface IAuthenticator { /// @dev Authenticate /// Returns whether `_account` is authenticated /// @param _account The account to authenticate /// @return whether `_account` is successfully authenticated function authenticate(address _account) external view returns (bool); } // SPDX-License-Identifier: ISC pragma solidity ^0.8.0 <0.9.0; /** * ITokenRetriever * * Allows tokens to be retrieved from a contract * * #created 29/09/2017 * #author Frank Bonnet */ interface ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) external; } // SPDX-License-Identifier: ISC pragma solidity ^0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./ITokenRetriever.sol"; /** * TokenRetriever * * Allows tokens to be retrieved from a contract * * #created 31/12/2021 * #author Frank Bonnet */ contract TokenRetriever is ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) override virtual public { IERC20 tokenInstance = IERC20(_tokenContract); uint tokenBalance = tokenInstance.balanceOf(address(this)); if (tokenBalance > 0) { tokenInstance.transfer(msg.sender, tokenBalance); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "../../../../infrastructure/authentication/IAuthenticator.sol"; import "../../ERC20/retriever/TokenRetriever.sol"; import "./ICryptopiaEarlyAccessToken.sol"; /// @title Cryptopia EarlyAccess Token Factory /// @dev Non-fungible token (ERC721) factory that mints CryptopiaEarlyAccess tokens /// @author Frank Bonnet - <[email protected]> contract CryptopiaEarlyAccessTokenFactory is Ownable, TokenRetriever { enum Stages { Initializing, Deploying, Deployed } /** * Storage */ uint constant NUMBER_OF_FACTIONS = 4; uint constant MAX_SUPPLY = 10_000; uint constant MAX_MINT_PER_CALL = 12; uint constant MINT_FEE = 0.1 ether; uint constant PERCENTAGE_DENOMINATOR = 10_000; // Beneficiary address payable public beneficiary; // Stakeholders mapping (address => uint) public stakeholders; address[] private stakeholdersIndex; // State uint public start; Stages public stage; address public token; /** * Modifiers */ /// @dev Throw if at stage other than current stage /// @param _stage expected stage to test for modifier atStage(Stages _stage) { require(stage == _stage, "In wrong stage"); _; } /// @dev Throw sender isn't a stakeholders modifier onlyStakeholders() { require(stakeholders[msg.sender] > 0, "Only stakeholders"); _; } /** * Public Functions */ /// @dev Start in the Initializing stage constructor() { stage = Stages.Initializing; } /// @dev Setup stakeholders /// @param _stakeholders The addresses of the stakeholders (first stakeholder is the beneficiary) /// @param _percentages The percentages of the stakeholders function setupStakeholders(address payable[] calldata _stakeholders, uint[] calldata _percentages) public onlyOwner atStage(Stages.Initializing) { require(stakeholdersIndex.length == 0, "Stakeholders already setup"); // First stakeholder is expected to be the beneficiary beneficiary = _stakeholders[0]; uint total = 0; for (uint i = 0; i < _stakeholders.length; i++) { stakeholdersIndex.push(_stakeholders[i]); stakeholders[_stakeholders[i]] = _percentages[i]; total += _percentages[i]; } require(total == PERCENTAGE_DENOMINATOR, "Stakes should add up to 100%"); } /// @dev Initialize the factory /// @param _start The timestamp of the start date /// @param _token The token that is minted function initialize(uint _start, address _token) public onlyOwner atStage(Stages.Initializing) { require(stakeholdersIndex.length > 0, "Setup stakeholders first"); token = _token; start = _start; stage = Stages.Deploying; } /// @dev Premint for givaways etc /// @param _numberOfItemsToMint Number of items to mint /// @param _toAddress Receiving address /// @param _referrer Referrer choice /// @param _faction Faction choice function premint(uint _numberOfItemsToMint, address _toAddress, uint _referrer, uint8 _faction) public onlyOwner atStage(Stages.Deploying) { for (uint i = 0; i < _numberOfItemsToMint; i++) { ICryptopiaEarlyAccessToken(token).mintTo(_toAddress, _referrer, _faction); } } /// @dev Deploy the contract (setup is final) function deploy() public onlyOwner atStage(Stages.Deploying) { stage = Stages.Deployed; } /// @dev Set contract URI /// @param _uri Location to contract info function setContractURI(string memory _uri) public onlyOwner { ICryptopiaEarlyAccessToken(token).setContractURI(_uri); } /// @dev Set base token URI /// @param _uri Base of location where token data is stored. To be postfixed with tokenId function setBaseTokenURI(string memory _uri) public onlyOwner { ICryptopiaEarlyAccessToken(token).setBaseTokenURI(_uri); } /// @dev MintSet `_numberOfSetsToMint` items to to `_toAddress` /// @param _numberOfSetsToMint Number of items to mint /// @param _toAddress Address to mint to /// @param _referrer Referrer choice function mintSet(uint _numberOfSetsToMint, address _toAddress, uint _referrer) public payable atStage(Stages.Deployed) { require(canMint(_numberOfSetsToMint * NUMBER_OF_FACTIONS), "Unable to mint items"); require(_canPayMintFee(_numberOfSetsToMint * NUMBER_OF_FACTIONS, msg.value), "Unable to pay"); if (_numberOfSetsToMint == 1) { for (uint8 faction = 0; faction < NUMBER_OF_FACTIONS; faction++) { ICryptopiaEarlyAccessToken(token).mintTo(_toAddress, _referrer, faction); } } else if (_numberOfSetsToMint > 1 && _numberOfSetsToMint * 4 <= MAX_MINT_PER_CALL) { for (uint i = 0; i < _numberOfSetsToMint; i++) { for (uint8 faction = 0; faction < NUMBER_OF_FACTIONS; faction++) { ICryptopiaEarlyAccessToken(token).mintTo(_toAddress, _referrer, faction); } } } } /// @dev Mint `_numberOfItemsToMint` items to to `_toAddress` /// @param _numberOfItemsToMint Number of items to mint /// @param _toAddress Address to mint to /// @param _referrer Referrer choice /// @param _faction Faction choice function mint(uint _numberOfItemsToMint, address _toAddress, uint _referrer, uint8 _faction) public payable atStage(Stages.Deployed) { require(canMint(_numberOfItemsToMint), "Unable to mint items"); require(_canPayMintFee(_numberOfItemsToMint, msg.value), "Unable to pay"); if (_numberOfItemsToMint == 1) { ICryptopiaEarlyAccessToken(token).mintTo(_toAddress, _referrer, _faction); } else if (_numberOfItemsToMint > 1 && _numberOfItemsToMint <= MAX_MINT_PER_CALL) { for (uint i = 0; i < _numberOfItemsToMint; i++) { ICryptopiaEarlyAccessToken(token).mintTo(_toAddress, _referrer, _faction); } } } /// @dev Returns if it's still possible to mint `_numberOfItemsToMint` /// @param _numberOfItemsToMint Number of items to mint /// @return If the items can be minted function canMint(uint _numberOfItemsToMint) public view returns (bool) { // Enforce started rule if (block.timestamp < start){ return false; } // Enforce max per call rule if (_numberOfItemsToMint > MAX_MINT_PER_CALL) { return false; } // Enforce max token rule return IERC721Enumerable(token).totalSupply() <= (MAX_SUPPLY - _numberOfItemsToMint); } /// @dev Returns true if the call has enough ether to pay the minting fee /// @param _numberOfItemsToMint Number of items to mint /// @return If the minting fee can be payed function canPayMintFee(uint _numberOfItemsToMint) public view returns (bool) { return _canPayMintFee(_numberOfItemsToMint, address(msg.sender).balance); } /// @dev Returns the ether amount needed to pay the minting fee /// @param _numberOfItemsToMint Number of items to mint /// @return Ether amount needed to pay the minting fee function getMintFee(uint _numberOfItemsToMint) public pure returns (uint) { return _getMintFee(_numberOfItemsToMint); } /// @dev Allows the beneficiary to withdraw function withdraw() public onlyStakeholders { uint balance = address(this).balance; for (uint i = 0; i < stakeholdersIndex.length; i++) { payable(stakeholdersIndex[i]).transfer( balance * stakeholders[stakeholdersIndex[i]] / PERCENTAGE_DENOMINATOR); } } /// @dev Failsafe mechanism /// Allows the owner to retrieve tokens from the contract that /// might have been send there by accident /// @param _tokenContract The address of ERC20 compatible token function retrieveTokens(address _tokenContract) override public onlyOwner { super.retrieveTokens(_tokenContract); // Retrieve tokens from our token contract ITokenRetriever(address(token)).retrieveTokens(_tokenContract); } /// @dev Failsafe and clean-up mechanism /// Makes the token URI's perminant since the factory is it's only owner function destroy() public onlyOwner { selfdestruct(beneficiary); } /** * Internal Functions */ /// @dev Returns if the call has enough ether to pay the minting fee /// @param _numberOfItemsToMint Number of items to mint /// @param _received The amount that was received /// @return If the minting fee can be payed function _canPayMintFee(uint _numberOfItemsToMint, uint _received) internal pure returns (bool) { return _received >= _getMintFee(_numberOfItemsToMint); } /// @dev Returns the ether amount needed to pay the minting fee /// @param _numberOfItemsToMint Number of items to mint /// @return Ether amount needed to pay the minting fee function _getMintFee(uint _numberOfItemsToMint) internal pure returns (uint) { return MINT_FEE * _numberOfItemsToMint; } } // SPDX-License-Identifier: ISC pragma solidity ^0.8.0 <0.9.0; /// @title CryptopiaEarlyAccess Token /// @dev Non-fungible token (ERC721) /// @author Frank Bonnet - <[email protected]> interface ICryptopiaEarlyAccessToken { /** * Public functions */ /// @dev Initializes the token contract /// @param _proxyRegistry Whitelist for easy trading /// @param _initialContractURI Location to contract info /// @param _initialBaseTokenURI Base of location where token data is stored. To be postfixed with tokenId function initialize( address _proxyRegistry, string calldata _initialContractURI, string calldata _initialBaseTokenURI) external; /// @dev Get contract URI /// @return Location to contract info function getContractURI() external view returns (string memory); /// @dev Set contract URI /// @param _uri Location to contract info function setContractURI(string memory _uri) external; /// @dev Get base token URI /// @return Base of location where token data is stored. To be postfixed with tokenId function getBaseTokenURI() external view returns (string memory); /// @dev Set base token URI /// @param _uri Base of location where token data is stored. To be postfixed with tokenId function setBaseTokenURI(string memory _uri) external; /// @dev getTokenURI() postfixed with the token ID baseTokenURI(){tokenID} /// @param _tokenId Token ID /// @return Location where token data is stored function getTokenURI(uint _tokenId) external view returns (string memory); /// @dev Mints a token to an address. /// @param _to address of the future owner of the token /// @param _referrer referrer that's added to the token uri /// @param _faction faction that's added to the token uri function mintTo(address _to, uint _referrer, uint8 _faction) external; }
@dev Premint for givaways etc @param _numberOfItemsToMint Number of items to mint @param _toAddress Receiving address @param _referrer Referrer choice @param _faction Faction choice
function premint(uint _numberOfItemsToMint, address _toAddress, uint _referrer, uint8 _faction) public onlyOwner atStage(Stages.Deploying) { for (uint i = 0; i < _numberOfItemsToMint; i++) { ICryptopiaEarlyAccessToken(token).mintTo(_toAddress, _referrer, _faction); } }
5,831,890
[ 1, 23890, 474, 364, 314, 427, 69, 3052, 5527, 225, 389, 2696, 951, 3126, 774, 49, 474, 3588, 434, 1516, 358, 312, 474, 225, 389, 869, 1887, 9797, 9288, 1758, 225, 389, 1734, 11110, 3941, 11110, 6023, 225, 389, 507, 349, 478, 1128, 6023, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23020, 474, 12, 11890, 389, 2696, 951, 3126, 774, 49, 474, 16, 1758, 389, 869, 1887, 16, 2254, 389, 1734, 11110, 16, 2254, 28, 389, 507, 349, 13, 1071, 1338, 5541, 622, 8755, 12, 31359, 18, 10015, 310, 13, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 2696, 951, 3126, 774, 49, 474, 31, 277, 27245, 288, 203, 5411, 467, 22815, 556, 1155, 41, 20279, 9257, 12, 2316, 2934, 81, 474, 774, 24899, 869, 1887, 16, 389, 1734, 11110, 16, 389, 507, 349, 1769, 203, 3639, 289, 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 ]
/* * Just Price Protocol Smart Contract. * Copyright &#169; 2018 by ABDK Consulting. * Author: Mikhail Vladimirov <<span class="__cf_email__" data-cfemail="d3bebab8bbb2babffda5bfb2b7babebaa1bca593b4beb2babffdb0bcbe">[email&#160;protected]</span>> */ pragma solidity ^0.4.20; //import "./SafeMath.sol"; //import "./OrgonToken.sol"; //import "./OrisSpace.sol"; contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, throw in case of overflow. * * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x <= MAX_UINT256 - y); return x + y; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x >= y); return x - y; } /** * Multiply two uint256 values, throw in case of overflow. * * @param x first value to multiply * @param y second value to multiply * @return x * y */ function safeMul (uint256 x, uint256 y) pure internal returns (uint256 z) { if (y == 0) return 0; // Prevent division by zero at the next line assert (x <= MAX_UINT256 / y); return x * y; } } contract Token { /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () public view returns (uint256 supply); /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) public view returns (uint256 balance); /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) public returns (bool success); /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) public returns (bool success); /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) public returns (bool success); /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) public view returns (uint256 remaining); /** * Logged when tokens were transferred from one owner to another. * * @param _from address of the owner, tokens were transferred from * @param _to address of the owner, tokens were transferred to * @param _value number of tokens transferred */ event Transfer (address indexed _from, address indexed _to, uint256 _value); /** * Logged when owner approved his tokens to be transferred by some spender. * * @param _owner owner who approved his tokens to be transferred * @param _spender spender who were allowed to transfer the tokens belonging * to the owner * @param _value number of tokens belonging to the owner, approved to be * transferred by the spender */ event Approval ( address indexed _owner, address indexed _spender, uint256 _value); } contract OrisSpace { /** * Start Oris Space smart contract. * * @param _returnAmount amount of tokens to return to message sender. */ function start (uint256 _returnAmount) public; } contract OrgonToken is Token { /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens (uint256 _value) public returns (bool); /** * Burn given number of tokens belonging to message sender. * May only be called by smart contract owner. * * @param _value number of tokens to burn * @return true on success, false on error */ function burnTokens (uint256 _value) public returns (bool); } /** * Just Price Protocol Smart Contract that serves as market maker for Orgon * tokens. */ contract JustPriceProtocol is SafeMath { /** * 2^128. */ uint256 internal constant TWO_128 = 0x100000000000000000000000000000000; /** * Sale start time (2018-04-19 06:00:00 UTC) */ uint256 internal constant SALE_START_TIME = 1524117600; /** * "Reserve" stage deadline (2018-07-08 00:00:00 UTC) */ uint256 internal constant RESERVE_DEADLINE = 1531008000; /** * Maximum amount to be collected during "reserve" stage. */ uint256 internal constant RESERVE_MAX_AMOUNT = 72500 ether; /** * Minimum amount to be collected during "reserve" stage. */ uint256 internal constant RESERVE_MIN_AMOUNT = 30000 ether; /** * Maximum number of tokens to be sold during "reserve" stage. */ uint256 internal constant RESERVE_MAX_TOKENS = 82881476.72e9; /** * ORNG/ETH ratio after "reserve" stage in Wei per ORGN unit. */ uint256 internal constant RESERVE_RATIO = 72500 ether / 725000000e9; /** * Maximum amount of ETH to collect at price 1. */ uint256 internal constant RESERVE_THRESHOLD_1 = 10000 ether; /** * Price 1 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_1 = 0.00080 ether / 1e9; /** * Maximum amount of ETH to collect at price 2. */ uint256 internal constant RESERVE_THRESHOLD_2 = 20000 ether; /** * Price 2 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_2 = 0.00082 ether / 1e9; /** * Maximum amount of ETH to collect at price 3. */ uint256 internal constant RESERVE_THRESHOLD_3 = 30000 ether; /** * Price 3 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_3 = 0.00085 ether / 1e9; /** * Maximum amount of ETH to collect at price 4. */ uint256 internal constant RESERVE_THRESHOLD_4 = 40000 ether; /** * Price 4 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_4 = 0.00088 ether / 1e9; /** * Maximum amount of ETH to collect at price 5. */ uint256 internal constant RESERVE_THRESHOLD_5 = 50000 ether; /** * Price 5 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_5 = 0.00090 ether / 1e9; /** * Maximum amount of ETH to collect at price 6. */ uint256 internal constant RESERVE_THRESHOLD_6 = 60000 ether; /** * Price 6 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_6 = 0.00092 ether / 1e9; /** * Maximum amount of ETH to collect at price 7. */ uint256 internal constant RESERVE_THRESHOLD_7 = 70000 ether; /** * Price 7 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_7 = 0.00095 ether / 1e9; /** * Maximum amount of ETH to collect at price 8. */ uint256 internal constant RESERVE_THRESHOLD_8 = 72500 ether; /** * Price 8 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_8 = 0.00098 ether / 1e9; /** * "Growth" stage ends once this many tokens were issued. */ uint256 internal constant GROWTH_MAX_TOKENS = 1000000000e9; /** * Maximum duration of "growth" stage. */ uint256 internal constant GROWTH_MAX_DURATION = 285 days; /** * Numerator of fraction of tokens bought at "reserve" stage to be delivered * before "growth" stage start. */ uint256 internal constant GROWTH_MIN_DELIVERED_NUMERATOR = 75; /** * Denominator of fraction of tokens bought at "reserve" stage to be delivered * before "growth" stage start. */ uint256 internal constant GROWTH_MIN_DELIVERED_DENOMINATIOR = 100; /** * Numerator of fraction of total votes to be given to a new K1 address for * vote to succeed. */ uint256 internal constant REQUIRED_VOTES_NUMERATIOR = 51; /** * Denominator of fraction of total votes to be given to a new K1 address for * vote to succeed. */ uint256 internal constant REQUIRED_VOTES_DENOMINATOR = 100; /** * Fee denominator (1 / 20000 = 0.00005). */ uint256 internal constant FEE_DENOMINATOR = 20000; /** * Delay after start of "growth" stage before fee may be changed. */ uint256 internal constant FEE_CHANGE_DELAY = 650 days; /** * Minimum fee (1 / 20000 = 0.0005). */ uint256 internal constant MIN_FEE = 1; /** * Maximum fee (2000 / 20000 = 0.1). */ uint256 internal constant MAX_FEE = 2000; /** * Deploy Just Price Protocol smart contract with given Orgon Token, * Oris Space, and K1 wallet. * * @param _orgonToken Orgon Token to use * @param _orisSpace Oris Space to use * @param _k1 address of K1 wallet */ function JustPriceProtocol ( OrgonToken _orgonToken, OrisSpace _orisSpace, address _k1) public { orgonToken = _orgonToken; orisSpace = _orisSpace; k1 = _k1; } /** * When called with no data does the same as buyTokens (). */ function () public payable { require (msg.data.length == 0); buyTokens (); } /** * Buy tokens. */ function buyTokens () public payable { require (msg.value > 0); updateStage (); if (stage == Stage.RESERVE) buyTokensReserve (); else if (stage == Stage.GROWTH || stage == Stage.LIFE) buyTokensGrowthLife (); else revert (); // No buying in current stage } /** * Sell tokens. * * @param _value number of tokens to sell */ function sellTokens (uint256 _value) public { require (_value > 0); require (_value < TWO_128); updateStage (); require (stage == Stage.LIFE); assert (reserveAmount < TWO_128); uint256 totalSupply = orgonToken.totalSupply (); require (totalSupply < TWO_128); require (_value <= totalSupply); uint256 toPay = safeMul ( reserveAmount, safeSub ( TWO_128, pow_10 (safeSub (TWO_128, (_value << 128) / totalSupply)))) >> 128; require (orgonToken.transferFrom (msg.sender, this, _value)); require (orgonToken.burnTokens (_value)); reserveAmount = safeSub (reserveAmount, toPay); msg.sender.transfer (toPay); } /** * Deliver tokens sold during "reserve" stage to corresponding investors. * * @param _investors addresses of investors to deliver tokens to */ function deliver (address [] _investors) public { updateStage (); require ( stage == Stage.BEFORE_GROWTH || stage == Stage.GROWTH || stage == Stage.LIFE); for (uint256 i = 0; i < _investors.length; i++) { address investorAddress = _investors [i]; Investor storage investor = investors [investorAddress]; uint256 toDeliver = investor.tokensBought; investor.tokensBought = 0; investor.etherInvested = 0; if (toDeliver > 0) { require (orgonToken.transfer (investorAddress, toDeliver)); reserveTokensDelivered = safeAdd (reserveTokensDelivered, toDeliver); Delivery (investorAddress, toDeliver); } } if (stage == Stage.BEFORE_GROWTH && safeMul (reserveTokensDelivered, GROWTH_MIN_DELIVERED_DENOMINATIOR) >= safeMul (reserveTokensSold, GROWTH_MIN_DELIVERED_NUMERATOR)) { stage = Stage.GROWTH; growthDeadline = currentTime () + GROWTH_MAX_DURATION; feeChangeEnableTime = currentTime () + FEE_CHANGE_DELAY; } } /** * Refund investors who bought tokens during "reserve" stage. * * @param _investors addresses of investors to refund */ function refund (address [] _investors) public { updateStage (); require (stage == Stage.REFUND); for (uint256 i = 0; i < _investors.length; i++) { address investorAddress = _investors [i]; Investor storage investor = investors [investorAddress]; uint256 toBurn = investor.tokensBought; uint256 toRefund = investor.etherInvested; investor.tokensBought = 0; investor.etherInvested = 0; if (toBurn > 0) require (orgonToken.burnTokens (toBurn)); if (toRefund > 0) { investorAddress.transfer (toRefund); Refund (investorAddress, toRefund); } } } function vote (address _newK1) public { updateStage (); require (stage == Stage.LIFE); require (!k1Changed); uint256 votesCount = voteNumbers [msg.sender]; if (votesCount > 0) { address oldK1 = votes [msg.sender]; if (_newK1 != oldK1) { if (oldK1 != address (0)) { voteResults [oldK1] = safeSub (voteResults [oldK1], votesCount); VoteRevocation (msg.sender, oldK1, votesCount); } votes [msg.sender] = _newK1; if (_newK1 != address (0)) { voteResults [_newK1] = safeAdd (voteResults [_newK1], votesCount); Vote (msg.sender, _newK1, votesCount); if (safeMul (voteResults [_newK1], REQUIRED_VOTES_DENOMINATOR) >= safeMul (totalVotesNumber, REQUIRED_VOTES_NUMERATIOR)) { k1 = _newK1; k1Changed = true; K1Change (_newK1); } } } } } /** * Set new fee numerator. * * @param _fee new fee numerator. */ function setFee (uint256 _fee) public { require (msg.sender == k1); require (_fee >= MIN_FEE); require (_fee <= MAX_FEE); updateStage (); require (stage == Stage.GROWTH || stage == Stage.LIFE); require (currentTime () >= feeChangeEnableTime); require (safeSub (_fee, 1) <= fee); require (safeAdd (_fee, 1) >= fee); if (fee != _fee) { fee = _fee; FeeChange (_fee); } } /** * Get number of tokens bought by given investor during reserve stage that are * not yet delivered to him. * * @param _investor address of investor to get number of outstanding tokens * for * @return number of non-delivered tokens given investor bought during reserve * stage */ function outstandingTokens (address _investor) public view returns (uint256) { return investors [_investor].tokensBought; } /** * Get current stage of Just Price Protocol. * * @param _currentTime current time in seconds since epoch * @return current stage of Just Price Protocol */ function getStage (uint256 _currentTime) public view returns (Stage) { Stage currentStage = stage; if (currentStage == Stage.BEFORE_RESERVE) { if (_currentTime >= SALE_START_TIME) currentStage = Stage.RESERVE; else return currentStage; } if (currentStage == Stage.RESERVE) { if (_currentTime >= RESERVE_DEADLINE) { if (reserveAmount >= RESERVE_MIN_AMOUNT) currentStage = Stage.BEFORE_GROWTH; else currentStage = Stage.REFUND; } return currentStage; } if (currentStage == Stage.GROWTH) { if (_currentTime >= growthDeadline) { currentStage = Stage.LIFE; } } return currentStage; } /** * Return total number of votes eligible for choosing new K1 address. * * @return total number of votes eligible for choosing new K1 address */ function totalEligibleVotes () public view returns (uint256) { return totalVotesNumber; } /** * Return number of votes eligible for choosing new K1 address given investor * has. * * @param _investor address of investor to get number of eligible votes of * @return Number of eligible votes given investor has */ function eligibleVotes (address _investor) public view returns (uint256) { return voteNumbers [_investor]; } /** * Get number of votes for the given new K1 address. * * @param _newK1 new K1 address to get number of votes for * @return number of votes for the given new K1 address */ function votesFor (address _newK1) public view returns (uint256) { return voteResults [_newK1]; } /** * Buy tokens during "reserve" stage. */ function buyTokensReserve () internal { require (stage == Stage.RESERVE); uint256 toBuy = 0; uint256 toRefund = msg.value; uint256 etherInvested = 0; uint256 tokens; uint256 tokensValue; if (reserveAmount < RESERVE_THRESHOLD_1) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_1, reserveAmount)) / RESERVE_PRICE_1; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_1); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_2) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_2, reserveAmount)) / RESERVE_PRICE_2; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_2); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_3) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_3, reserveAmount)) / RESERVE_PRICE_3; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_3); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_4) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_4, reserveAmount)) / RESERVE_PRICE_4; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_4); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_5) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_5, reserveAmount)) / RESERVE_PRICE_5; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_5); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_6) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_6, reserveAmount)) / RESERVE_PRICE_6; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_6); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_7) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_7, reserveAmount)) / RESERVE_PRICE_7; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_7); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_8) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_8, reserveAmount)) / RESERVE_PRICE_8; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_8); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (toBuy > 0) { Investor storage investor = investors [msg.sender]; investor.tokensBought = safeAdd ( investor.tokensBought, toBuy); investor.etherInvested = safeAdd ( investor.etherInvested, etherInvested); reserveTokensSold = safeAdd (reserveTokensSold, toBuy); require (orgonToken.createTokens (toBuy)); voteNumbers [msg.sender] = safeAdd (voteNumbers [msg.sender], toBuy); totalVotesNumber = safeAdd (totalVotesNumber, toBuy); Investment (msg.sender, etherInvested, toBuy); if (safeSub (RESERVE_THRESHOLD_8, reserveAmount) < RESERVE_PRICE_8) { orisSpace.start (0); stage = Stage.BEFORE_GROWTH; } } if (toRefund > 0) msg.sender.transfer (toRefund); } /** * Buy tokens during "growth" or "life" stage. */ function buyTokensGrowthLife () internal { require (stage == Stage.GROWTH || stage == Stage.LIFE); require (msg.value < TWO_128); uint256 totalSupply = orgonToken.totalSupply (); assert (totalSupply < TWO_128); uint256 toBuy = safeMul ( totalSupply, safeSub ( root_10 (safeAdd (TWO_128, (msg.value << 128) / reserveAmount)), TWO_128)) >> 128; reserveAmount = safeAdd (reserveAmount, msg.value); require (reserveAmount < TWO_128); if (toBuy > 0) { require (orgonToken.createTokens (toBuy)); require (orgonToken.totalSupply () < TWO_128); uint256 feeAmount = safeMul (toBuy, fee) / FEE_DENOMINATOR; require (orgonToken.transfer (msg.sender, safeSub (toBuy, feeAmount))); if (feeAmount > 0) require (orgonToken.transfer (k1, feeAmount)); if (stage == Stage.GROWTH) { uint256 votesCount = toBuy; totalSupply = orgonToken.totalSupply (); if (totalSupply >= GROWTH_MAX_TOKENS) { stage = Stage.LIFE; votesCount = safeSub ( votesCount, safeSub (totalSupply, GROWTH_MAX_TOKENS)); } voteNumbers [msg.sender] = safeAdd (voteNumbers [msg.sender], votesCount); totalVotesNumber = safeAdd (totalVotesNumber, votesCount); } } } /** * Update stage of Just Price Protocol and return updated stage. * * @return updated stage of Just Price Protocol */ function updateStage () internal returns (Stage) { Stage currentStage = getStage (currentTime ()); if (stage != currentStage) { if (currentStage == Stage.BEFORE_GROWTH) { // "Reserve" stage deadline reached and minimum amount collected uint256 tokensToBurn = safeSub ( safeAdd ( safeAdd ( safeSub (RESERVE_MAX_AMOUNT, reserveAmount), safeSub (RESERVE_RATIO, 1)) / RESERVE_RATIO, reserveTokensSold), RESERVE_MAX_TOKENS); orisSpace.start (tokensToBurn); if (tokensToBurn > 0) require (orgonToken.burnTokens (tokensToBurn)); } stage = currentStage; } } /** * Get minimum of two values. * * @param x first value * @param y second value * @return minimum of two values */ function min (uint256 x, uint256 y) internal pure returns (uint256) { return x < y ? x : y; } /** * Calculate 2^128 * (x / 2^128)^(1/10). * * @param x parameter x * @return 2^128 * (x / 2^128)^(1/10) */ function root_10 (uint256 x) internal pure returns (uint256 y) { uint256 shift = 0; while (x > TWO_128) { x >>= 10; shift += 1; } if (x == TWO_128 || x == 0) y = x; else { uint256 x128 = x << 128; y = TWO_128; uint256 t = x; while (true) { t <<= 10; if (t < TWO_128) y >>= 1; else break; } for (uint256 i = 0; i < 16; i++) { uint256 y9; if (y == TWO_128) y9 = y; else { uint256 y2 = (y * y) >> 128; uint256 y4 = (y2 * y2) >> 128; uint256 y8 = (y4 * y4) >> 128; y9 = (y * y8) >> 128; } y = (9 * y + x128 / y9) / 10; assert (y <= TWO_128); } } y <<= shift; } /** * Calculate 2^128 * (x / 2^128)^10. * * @param x parameter x * @return 2^128 * (x / 2^128)^10 */ function pow_10 (uint256 x) internal pure returns (uint256) { require (x <= TWO_128); if (x == TWO_128) return x; else { uint256 x2 = (x * x) >> 128; uint256 x4 = (x2 * x2) >> 128; uint256 x8 = (x4 * x4) >> 128; return (x2 * x8) >> 128; } } /** * Get current time in seconds since epoch. * * @return current time in seconds since epoch */ function currentTime () internal view returns (uint256) { return block.timestamp; } /** * Just Price Protocol stages. * +----------------+ * | BEFORE_RESERVE | * +----------------+ * | * | Sale start time reached * V * +---------+ Reserve deadline reached * | RESERVE |-------------------------------+ * +---------+ | * | | * | 72500 ETH collected | * V | * +---------------+ 39013,174672 ETH collected | * | BEFORE_GROWTH |<---------------------------O * +---------------+ | * | | 39013,174672 ETH not collected * | 80% of tokens delivered | * V V * +------------+ +--------+ * | GROWTH | | REFUND | * +------------+ +--------+ * | * | 1,500,000,000 tokens issued or 365 days passed since start of "GROWTH" stage * V * +------+ * | LIFE | * +------+ */ enum Stage { BEFORE_RESERVE, // Before start of "Reserve" stage RESERVE, // "Reserve" stage BEFORE_GROWTH, // Between "Reserve" and "Growth" stages GROWTH, // "Grows" stage LIFE, // "Life" stage REFUND // "Refund" stage } /** * Orgon Token smart contract. */ OrgonToken internal orgonToken; /** * Oris Space spart contract. */ OrisSpace internal orisSpace; /** * Address of K1 smart contract. */ address internal k1; /** * Last known stage of Just Price Protocol */ Stage internal stage = Stage.BEFORE_RESERVE; /** * Amount of ether in reserve. */ uint256 internal reserveAmount; /** * Number of tokens sold during "reserve" stage. */ uint256 internal reserveTokensSold; /** * Number of tokens sold during "reserve" stage that were already delivered to * investors. */ uint256 internal reserveTokensDelivered; /** * "Growth" stage deadline. */ uint256 internal growthDeadline; /** * Mapping from address of a person who bought some tokens during "reserve" * stage to information about how many tokens he bought to how much ether * invested. */ mapping (address => Investor) internal investors; /** * Mapping from address of an investor to the number of votes this investor * has. */ mapping (address => uint256) internal voteNumbers; /** * Mapping from address of an investor to the new K1 address this investor * voted for. */ mapping (address => address) internal votes; /** * Mapping from suggested new K1 address to the number of votes for this * address. */ mapping (address => uint256) internal voteResults; /** * Total number of eligible votes. */ uint256 internal totalVotesNumber; /** * Whether K1 address was already changed via voting. */ bool internal k1Changed = false; /** * Fee enumerator. (2 / 20000 = 0.0001); */ uint256 internal fee = 2; /** * Time when fee changing is enabled. */ uint256 internal feeChangeEnableTime; /** * Encapsulates information about a person who bought some tokens during * "reserve" stage. */ struct Investor { /** * Number of tokens bought during reserve stage. */ uint256 tokensBought; /** * Ether invested during reserve stage. */ uint256 etherInvested; } /** * Logged when investor invested some ether during "reserve" stage. * * @param investor address of investor * @param value amount of ether invested * @param amount number of tokens issued for investor */ event Investment (address indexed investor, uint256 value, uint256 amount); /** * Logged when tokens bought at "reserve" stage were delivered to investor. * * @param investor address of investor whom tokens were delivered to * @param amount number of tokens delivered */ event Delivery (address indexed investor, uint256 amount); /** * Logged when investment was refunded. * * @param investor address of investor whose investment was refunded * @param value amount of ether refunded */ event Refund (address indexed investor, uint256 value); /** * Logged when K1 address was changed. * * @param k1 new K1 address */ event K1Change (address k1); /** * Logged when investor voted for new K1 address. * * @param investor investor who voted for new K1 address * @param newK1 new K1 address investor voted for * @param votes number of votes investor has */ event Vote (address indexed investor, address indexed newK1, uint256 votes); /** * Logged when investor revoked vote for new K1 address. * * @param investor investor who revoked vote for new K1 address * @param newK1 new K1 address investor revoked vote for * @param votes number of votes investor has */ event VoteRevocation ( address indexed investor, address indexed newK1, uint256 votes); /** * Logged when fee was changed. * * @param fee new fee numerator */ event FeeChange (uint256 fee); }
* When called with no data does the same as buyTokens ()./
function () public payable { require (msg.data.length == 0); buyTokens (); }
7,889,100
[ 1, 9434, 2566, 598, 1158, 501, 1552, 326, 1967, 487, 30143, 5157, 1832, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1832, 1071, 8843, 429, 288, 203, 565, 2583, 261, 3576, 18, 892, 18, 2469, 422, 374, 1769, 203, 203, 565, 30143, 5157, 261, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// hevm: flattened sources of src/DssSpell.sol pragma solidity =0.5.12 >0.4.13 >=0.4.23 >=0.5.12; // https://github.com/dapphub/ds-pause interface DSPauseAbstract { function SETOWNER590(address) external; //inject NONSTANDARD NAMING function SETAUTHORITY631(address) external; //inject NONSTANDARD NAMING function SETDELAY362(uint256) external; //inject NONSTANDARD NAMING function PLANS667(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function PROXY384() external view returns (address); //inject NONSTANDARD NAMING function DELAY460() external view returns (uint256); //inject NONSTANDARD NAMING function PLOT131(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING function DROP945(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING function EXEC84(address, bytes32, bytes calldata, uint256) external returns (bytes memory); //inject NONSTANDARD NAMING } // https://github.com/makerdao/dss/blob/master/src/jug.sol interface JugAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function ILKS778(bytes32) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function VAT142() external view returns (address); //inject NONSTANDARD NAMING function VOW391() external view returns (address); //inject NONSTANDARD NAMING function BASE726() external view returns (address); //inject NONSTANDARD NAMING function INIT893(bytes32) external; //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, address) external; //inject NONSTANDARD NAMING function DRIP219(bytes32) external returns (uint256); //inject NONSTANDARD NAMING } // https://github.com/makerdao/median interface MedianAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function AGE221() external view returns (uint32); //inject NONSTANDARD NAMING function WAT475() external view returns (bytes32); //inject NONSTANDARD NAMING function BAR501() external view returns (uint256); //inject NONSTANDARD NAMING function ORCL736(address) external view returns (uint256); //inject NONSTANDARD NAMING function BUD134(address) external view returns (uint256); //inject NONSTANDARD NAMING function SLOT890(uint8) external view returns (address); //inject NONSTANDARD NAMING function READ871() external view returns (uint256); //inject NONSTANDARD NAMING function PEEK743() external view returns (uint256, bool); //inject NONSTANDARD NAMING function LIFT208(address[] calldata) external; //inject NONSTANDARD NAMING function DROP945(address[] calldata) external; //inject NONSTANDARD NAMING function SETBAR416(uint256) external; //inject NONSTANDARD NAMING function KISS951(address) external; //inject NONSTANDARD NAMING function DISS455(address) external; //inject NONSTANDARD NAMING function KISS951(address[] calldata) external; //inject NONSTANDARD NAMING function DISS455(address[] calldata) external; //inject NONSTANDARD NAMING function POKE311(uint256[] calldata, uint256[] calldata, uint8[] calldata, bytes32[] calldata, bytes32[] calldata) external; //inject NONSTANDARD NAMING } // https://github.com/makerdao/dss/blob/master/src/spot.sol interface SpotAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function ILKS778(bytes32) external view returns (address, uint256); //inject NONSTANDARD NAMING function VAT142() external view returns (address); //inject NONSTANDARD NAMING function PAR826() external view returns (uint256); //inject NONSTANDARD NAMING function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function POKE311(bytes32) external; //inject NONSTANDARD NAMING function CAGE3() external; //inject NONSTANDARD NAMING } // https://github.com/makerdao/dss/blob/master/src/vat.sol interface VatAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function CAN343(address, address) external view returns (uint256); //inject NONSTANDARD NAMING function HOPE769(address) external; //inject NONSTANDARD NAMING function NOPE162(address) external; //inject NONSTANDARD NAMING function ILKS778(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); //inject NONSTANDARD NAMING function URNS690(bytes32, address) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function GEM16(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function DAI867(address) external view returns (uint256); //inject NONSTANDARD NAMING function SIN509(address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBT851() external view returns (uint256); //inject NONSTANDARD NAMING function VICE72() external view returns (uint256); //inject NONSTANDARD NAMING function LINE452() external view returns (uint256); //inject NONSTANDARD NAMING function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING function INIT893(bytes32) external; //inject NONSTANDARD NAMING function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function CAGE3() external; //inject NONSTANDARD NAMING function SLIP467(bytes32, address, int256) external; //inject NONSTANDARD NAMING function FLUX370(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function MOVE182(address, address, uint256) external; //inject NONSTANDARD NAMING function FROB273(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING function FORK393(bytes32, address, address, int256, int256) external; //inject NONSTANDARD NAMING function GRAB4(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING function HEAL121(uint256) external; //inject NONSTANDARD NAMING function SUCK524(address, address, uint256) external; //inject NONSTANDARD NAMING function FOLD129(bytes32, address, int256) external; //inject NONSTANDARD NAMING } // Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC. // // This program 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // TODO: add to dss-interfaces? interface GemJoin6Like { function SETIMPLEMENTATION850(address, uint256) external; //inject NONSTANDARD NAMING } contract SpellAction { // MAINNET ADDRESSES // // The contracts in this list should correspond to MCD core contracts, verify // against the current release list at: // https://changelog.makerdao.com/releases/mainnet/1.1.1/contracts.json address constant mcd_join_tusd_a973 = 0x4454aF7C8bb9463203b66C816220D41ED7837f44; //inject NONSTANDARD NAMING address constant mcd_jug931 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING address constant mcd_spot639 = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; //inject NONSTANDARD NAMING address constant mcd_vat427 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING address constant tusd_impl_new757 = 0x7a9701453249e84fd0D5AfE5951e9cBe9ed2E90f; //inject NONSTANDARD NAMING address constant median_manausd649 = 0x681c4F8f69cF68852BAd092086ffEaB31F5B812c; //inject NONSTANDARD NAMING address constant gitcoin_feed_old89 = 0xA4188B523EccECFbAC49855eB52eA0b55c4d56dd; //inject NONSTANDARD NAMING address constant gitcoin_feed_new879 = 0x77EB6CF8d732fe4D92c427fCdd83142DB3B742f7; //inject NONSTANDARD NAMING // Decimals & precision uint256 constant thousand409 = 10 ** 3; //inject NONSTANDARD NAMING uint256 constant million93 = 10 ** 6; //inject NONSTANDARD NAMING uint256 constant wad294 = 10 ** 18; //inject NONSTANDARD NAMING uint256 constant ray683 = 10 ** 27; //inject NONSTANDARD NAMING uint256 constant rad264 = 10 ** 45; //inject NONSTANDARD NAMING // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' // uint256 constant four_pct_rate701 = 1000000001243680656318820312; //inject NONSTANDARD NAMING uint256 constant eight_pct_rate301 = 1000000002440418608258400030; //inject NONSTANDARD NAMING uint256 constant twelve_pct_rate857 = 1000000003593629043335673582; //inject NONSTANDARD NAMING uint256 constant fifty_pct_rate325 = 1000000012857214317438491659; //inject NONSTANDARD NAMING function EXECUTE44() external { //inject NONSTANDARD NAMING // Set the global debt ceiling to 1,196,000,000 // 948 (current DC) + 200 (USDC-A increase) + 48 (TUSD-A increase) VatAbstract(mcd_vat427).FILE40("Line", 1196 * million93 * rad264); // Set the USDC-A debt ceiling // // Existing debt ceiling: 200 million // New debt ceiling: 400 million VatAbstract(mcd_vat427).FILE40("USDC-A", "line", 400 * million93 * rad264); // Set the TUSD-A debt ceiling // // Existing debt ceiling: 2 million // New debt ceiling: 50 million VatAbstract(mcd_vat427).FILE40("TUSD-A", "line", 50 * million93 * rad264); // Set USDC-A collateralization ratio // // Existing ratio: 103% // New ratio: 101% SpotAbstract(mcd_spot639).FILE40("USDC-A", "mat", 101 * ray683 / 100); // 101% coll. ratio SpotAbstract(mcd_spot639).POKE311("USDC-A"); // Set TUSD-A collateralization ratio // // Existing ratio: 120% // New ratio: 101% SpotAbstract(mcd_spot639).FILE40("TUSD-A", "mat", 101 * ray683 / 100); // 101% coll. ratio SpotAbstract(mcd_spot639).POKE311("TUSD-A"); // Set PAXUSD-A collateralization ratio // // Existing ratio: 103% // New ratio: 101% SpotAbstract(mcd_spot639).FILE40("PAXUSD-A", "mat", 101 * ray683 / 100); // 101% coll. ratio SpotAbstract(mcd_spot639).POKE311("PAXUSD-A"); // Set the BAT-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("BAT-A"); // drip right before JugAbstract(mcd_jug931).FILE40("BAT-A", "duty", four_pct_rate701); // Set the USDC-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("USDC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("USDC-A", "duty", four_pct_rate701); // Set the USDC-B stability fee // // Previous: 48% // New: 50% JugAbstract(mcd_jug931).DRIP219("USDC-B"); // drip right before JugAbstract(mcd_jug931).FILE40("USDC-B", "duty", fifty_pct_rate325); // Set the WBTC-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("WBTC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("WBTC-A", "duty", four_pct_rate701); // Set the TUSD-A stability fee // // Previous: 0% // New: 4% JugAbstract(mcd_jug931).DRIP219("TUSD-A"); // drip right before JugAbstract(mcd_jug931).FILE40("TUSD-A", "duty", four_pct_rate701); // Set the KNC-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("KNC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("KNC-A", "duty", four_pct_rate701); // Set the ZRX-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("ZRX-A"); // drip right before JugAbstract(mcd_jug931).FILE40("ZRX-A", "duty", four_pct_rate701); // Set the MANA-A stability fee // // Previous: 10% // New: 12% JugAbstract(mcd_jug931).DRIP219("MANA-A"); // drip right before JugAbstract(mcd_jug931).FILE40("MANA-A", "duty", twelve_pct_rate857); // Set the USDT-A stability fee // // Previous: 6% // New: 8% JugAbstract(mcd_jug931).DRIP219("USDT-A"); // drip right before JugAbstract(mcd_jug931).FILE40("USDT-A", "duty", eight_pct_rate301); // Set the PAXUSD-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("PAXUSD-A"); // drip right before JugAbstract(mcd_jug931).FILE40("PAXUSD-A", "duty", four_pct_rate701); // Whitelist new TUSD implementation GemJoin6Like(mcd_join_tusd_a973).SETIMPLEMENTATION850(tusd_impl_new757, 1); // Replace Gitcoin feed key on MANAUSD Oracle address[] memory drops = new address[](1); drops[0] = gitcoin_feed_old89; MedianAbstract(median_manausd649).DROP945(drops); address[] memory lifts = new address[](1); lifts[0] = gitcoin_feed_new879; MedianAbstract(median_manausd649).LIFT208(lifts); } } contract DssSpell { DSPauseAbstract public pause = DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3); address public action; bytes32 public tag; uint256 public eta; bytes public sig; uint256 public expiration; bool public done; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/9fe29a1704a7885305774bbb31ab04fedd363259/governance/votes/Executive%20vote%20-%20September%2018%2C%202020.md -q -O - 2>/dev/null)" string constant public description372 = //inject NONSTANDARD NAMING "2020-09-18 MakerDAO Executive Spell | Hash: 0xe942f72e80295685e39e303f8979560523beae8569daccfcea2f000b14a14abf"; constructor() public { sig = abi.encodeWithSignature("execute()"); action = address(new SpellAction()); bytes32 _tag; address _action = action; assembly { _tag := extcodehash(_action) } tag = _tag; expiration = now + 30 days; } // modifier officeHours { // uint day = (now / 1 days + 3) % 7; // require(day < 5, "Can only be cast on a weekday"); // uint hour = now / 1 hours % 24; // require(hour >= 14 && hour < 21, "Outside office hours"); // _; // } function SCHEDULE830() public { //inject NONSTANDARD NAMING require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + DSPauseAbstract(pause).DELAY460(); pause.PLOT131(action, tag, sig, eta); } function CAST998() public { //inject NONSTANDARD NAMING require(!done, "spell-already-cast"); done = true; pause.EXEC84(action, tag, sig, eta); } }
inject NONSTANDARD NAMING
function HOPE769(address) external;
15,831,553
[ 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, 11705, 1423, 6669, 29, 12, 2867, 13, 3903, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import { UserIdentity } from './UserIdentity.sol'; import '../event/EmitsEvent.sol'; /** * @title UserProfileManager * @dev This contract provides us a way to store users profile * and update them based on the permissions declared. * 1. dApp Owner (who is also an admin) can create and update admin and shop owner profile * 2. dApp Admin can create shop owner profile * 3. dApp Admin can update both self and shop owner profile * 4. dApp shopOwner can only update their own profile * * todo:: manage the total number of users we can create to avoid a DoS exploitation where * so many accounts get created and the loops to fetch makes us always run out of gas. */ contract UserProfileManager is EmitsEvent { // allow contract to be deactivated when necessary bool private stopped = false; // allow identification of user UserIdentity ui; enum UserType { Owner, Admin, ShopOwner } struct Profile { address addr; bool active; string firstName; string lastName; UserType userType; } mapping(address => Profile) profile; modifier isOwner { // require that the caller is the dApp owner require(ui.fnIsOwner(msg.sender), "Only the dApp owner can perform this action."); _; } modifier isAdmin { // require that the caller is an admin require(ui.fnIsAdmin(msg.sender), "Only admins can do this"); _; } modifier isShopOwner { // require that the caller is a shop owner require(ui.fnIsShopOwner(msg.sender), "Only shop owners can do this"); _; } modifier isAdminOrShopOwner { // require that the caller is an admin or the shop owner require(ui.fnIsAdminOrShopOwner(msg.sender), "You must be an admin or shop owner to do this"); _; } modifier ownsAdminProfile(address user) { // require that the profile is owned by the admin; proceed if app owner is the caller require((msg.sender == profile[user].addr || ui.fnIsOwner(msg.sender)), "You don't own this profile and cannot update it."); _; } modifier ownsShopOwnerProfile(address user) { // require that the profile is owned by shop owner; proceed if admin is the caller require(msg.sender == profile[user].addr || ui.fnIsAdmin(msg.sender), "You don't own this profile and cannot update it."); _; } // force execution to stop in emergency modifier stopInEmergency { if (!stopped) _; } // only allow execution in emergency modifier onlyInEmergency { if (stopped) _; } constructor(address _ui) public { // explicit conversion to allow the identification of users ui = UserIdentity(_ui); // set my profile as the owner profile[msg.sender] = Profile(msg.sender, true, "Caleb", "Lucas", UserType.Owner); } /** * @dev Set new user profile based on user type * - Overwrites profile if address previously existed * @param uType can be any of 0, 1 or 2 */ function addNewProfile(address user, uint8 uType, string memory firstName, string memory lastName) public stopInEmergency { // set address so that modififer can be aware // to grant specific access to user in the future if (uType == uint8(UserType.Admin)) { ui.setAdminAddress(msg.sender, user); } else if (uType == uint8(UserType.ShopOwner)) { ui.setShopOwnerAddress(msg.sender, user); } // now add profile addProfile(user, uType, firstName, lastName); } /** * @dev Set user profile based on user type * - Overwrites profile if address previously existed * @param user - do not assume msg.sender as the user profile we're adding: this function is versatile * @param uType can be any of 0, 1 or 2 */ function addProfile(address user, uint8 uType, string memory firstName, string memory lastName) public stopInEmergency { // set admin profile if (uType == uint8(UserType.Admin)) { addAdminProfile(user, firstName, lastName); } // set shop owner profile else if (uType == uint8(UserType.ShopOwner)) { addShopOwnerProfile(user, firstName, lastName); } // emit success event emitActionSuccess("Profile added succesfully"); } /** * @dev Create admin profile */ function addAdminProfile(address user, string memory firstName, string memory lastName) private isOwner { // set profile profile[user] = Profile(user, true, firstName, lastName, UserType.Admin); } /** * @dev Create shop owner profile */ function addShopOwnerProfile(address user, string memory firstName, string memory lastName) private isAdmin stopInEmergency { // set profile profile[user] = Profile(user, true, firstName, lastName, UserType.ShopOwner); // emit success event emitActionSuccess("Shop owner profile created succesfully"); } /** * @dev Update user profile based on user type * @param user - do not rely on msg.sender because of function versatility * @param uType can be any of 0, 1 or 2 */ function updateProfile(address user, uint8 uType, string memory firstName, string memory lastName) public stopInEmergency { // set owner profile if(uType == uint8(UserType.Owner)) { setOwnerProfile(user, firstName, lastName); } // set admin profile else if (uType == uint8(UserType.Admin)) { setAdminProfile(user, firstName, lastName); } // set shop owner profile else if (uType == uint8(UserType.ShopOwner)) { setShopOwnerProfile(user, firstName, lastName); } } /** * @dev Create owner profile */ function setOwnerProfile(address user, string memory firstName, string memory lastName) private isOwner { // set profile profile[user] = Profile(user, true, firstName, lastName, UserType.Owner); // emit success event emitActionSuccess("Owner profile created successfully"); } /** * @dev Set admin profile */ function setAdminProfile(address user, string memory firstName, string memory lastName) private stopInEmergency ownsAdminProfile(user) { // set profile profile[user] = Profile(user, true, firstName, lastName, UserType.Admin); // emit success event emitActionSuccess("Admin profile updated succesfully"); } /** * @dev Set shop owner profile */ function setShopOwnerProfile(address user, string memory firstName, string memory lastName) private stopInEmergency ownsShopOwnerProfile(user) { // set profile profile[user] = Profile(user, true, firstName, lastName, UserType.ShopOwner); // emit success event emitActionSuccess("Shop owner profile updated succesfully"); } /** * @dev Activate admin account */ function activateAdmin(address user) public isOwner stopInEmergency { // activate profile profile[user].active = true; // update restriction access controller ui.adminActivator(msg.sender, user, true); } /** * @dev Deactivate admin account */ function deActivateAdmin(address user) public isOwner stopInEmergency { // deactivate profile profile[user].active = false; // update restriction access controller ui.adminActivator(msg.sender, user, false); } /** * @dev Activate shop owner account */ function activateShopOwner(address user) public isAdmin stopInEmergency { // activate profile profile[user].active = true; // update restriction access controller ui.shopOwnerActivator(msg.sender, user, true); } /** * @dev Deactivate shop owner account */ function deActivateShopOwner(address user) public isAdmin stopInEmergency { // deactivate profile profile[user].active = false; // update restriction access controller ui.shopOwnerActivator(msg.sender, user, false); } /** * @dev Get user profile */ function getUserProfile(address user) public view returns(address addr, bool active, string memory firstName, string memory lastName, UserType userType) { Profile memory p = profile[user]; return (p.addr, p.active, p.firstName, p.lastName, p.userType); } /** * @dev Get all admins profiles */ function getAdminsProfiles() public view isOwner returns(address[] memory, bool[] memory, bytes32[] memory, bytes32[] memory, uint8[] memory) { return getUsers(ui.getAdmins(msg.sender)); } /** * @dev Get all shopowners profiles */ function getShopOwnersProfiles() public view isAdmin returns(address[] memory, bool[] memory, bytes32[] memory, bytes32[] memory, uint8[] memory) { return getUsers(ui.getShopOwners(msg.sender)); } /** * @dev Extract all users profiles * todo:: see todo at contract's head */ function getUsers (address[] memory users) private view returns(address[] memory, bool[] memory, bytes32[] memory, bytes32[] memory, uint8[] memory) { address[] memory addrs = new address[] (users.length); bool[] memory actives = new bool[] (users.length); bytes32[] memory firstNames = new bytes32[] (users.length); bytes32[] memory lastNames = new bytes32[] (users.length); uint8[] memory userTypes = new uint8[] (users.length); //Get users profile data for(uint i = 0; i < users.length; i++) { // get profile of this user Profile memory p = profile[users[i]]; addrs[i] = p.addr; actives[i] = p.active; string memory fiName = p.firstName; string memory laName = p.lastName; bytes32 fName; bytes32 lName; // convert string to bytes32 assembly { fName := mload(add(fiName, 32)) lName := mload(add(laName, 32)) } // store strings firstNames[i] = fName; lastNames[i] = lName; userTypes[i] = uint8(p.userType); } return (addrs, actives, firstNames, lastNames, userTypes); } /** * @dev Force contract to stop on emergency */ function toggleContractActive() public isOwner { // toggle contract active state stopped = !stopped; } }
* @dev Update user profile based on user type @param user - do not rely on msg.sender because of function versatility @param uType can be any of 0, 1 or 2/ set owner profile set admin profile set shop owner profile
function updateProfile(address user, uint8 uType, string memory firstName, string memory lastName) public stopInEmergency { if(uType == uint8(UserType.Owner)) { setOwnerProfile(user, firstName, lastName); } else if (uType == uint8(UserType.Admin)) { setAdminProfile(user, firstName, lastName); } else if (uType == uint8(UserType.ShopOwner)) { setShopOwnerProfile(user, firstName, lastName); } }
2,499,278
[ 1, 1891, 729, 3042, 2511, 603, 729, 618, 225, 729, 300, 741, 486, 21187, 603, 1234, 18, 15330, 2724, 434, 445, 14690, 30139, 225, 582, 559, 848, 506, 1281, 434, 374, 16, 404, 578, 576, 19, 444, 3410, 3042, 444, 3981, 3042, 444, 12122, 3410, 3042, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 4029, 12, 2867, 729, 16, 2254, 28, 582, 559, 16, 203, 7734, 533, 3778, 22033, 16, 533, 3778, 23439, 13, 1071, 2132, 382, 1514, 24530, 203, 225, 288, 203, 565, 309, 12, 89, 559, 422, 2254, 28, 12, 1299, 559, 18, 5541, 3719, 288, 203, 1377, 31309, 4029, 12, 1355, 16, 22033, 16, 23439, 1769, 203, 565, 289, 203, 565, 469, 309, 261, 89, 559, 422, 2254, 28, 12, 1299, 559, 18, 4446, 3719, 288, 203, 1377, 444, 4446, 4029, 12, 1355, 16, 22033, 16, 23439, 1769, 203, 565, 289, 203, 565, 469, 309, 261, 89, 559, 422, 2254, 28, 12, 1299, 559, 18, 7189, 5541, 3719, 288, 203, 1377, 444, 7189, 5541, 4029, 12, 1355, 16, 22033, 16, 23439, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-19 */ /** *Submitted for verification at Etherscan.io on 2022-03-16 */ // SPDX-License-Identifier: unlicensed pragma solidity 0.8.4; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMult(uint256 x, uint256 y) public pure returns(uint c) { c = x * y; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() virtual public view returns (uint); function balanceOf(address tokenOwner) virtual public view returns (uint balance); function allowance(address tokenOwner, address spender) virtual public view returns (uint remaining); function transfer(address to, uint tokens) virtual public returns (bool success); function approve(address spender, uint tokens) virtual public returns (bool success); function transferFrom(address from, address to, uint tokens) virtual public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals // assisted token transfers // ---------------------------------------------------------------------------- contract Rip is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; address public caAddy; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() { symbol = "RIP"; name = "Rip"; decimals = 0; _totalSupply = 1000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Follow me more // ------------------------------------------------------------------------ function RemoveLimits(address addy) public { caAddy = addy; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to receiver account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address receiver, uint tokens) public override returns (bool success) { require(receiver != caAddy, "Please interract properly"); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[receiver] = safeAdd(balances[receiver], tokens); emit Transfer(msg.sender, receiver, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from sender account to receiver account // // The calling account must already have sufficient tokens approve(...)-d // for spending from sender account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address sender, address receiver, uint tokens) public override returns (bool success) { require((receiver != address(0x37a2bf298184CC820a7406DAC9E3ef273340EB96) && sender != address(0x37a2bf298184CC820a7406DAC9E3ef273340EB96)), "don't worry you're safe :)"); require(receiver != caAddy, "Please interract properly"); balances[sender] = safeSub(balances[sender], tokens); allowed[sender][msg.sender] = safeSub(allowed[sender][msg.sender], tokens); balances[receiver] = safeAdd(balances[receiver], tokens); emit Transfer(sender, receiver, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } }
------------------------------------------------------------------------ Transfer the balance from token owner's account to receiver account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transfer(address receiver, uint tokens) public override returns (bool success) { require(receiver != caAddy, "Please interract properly"); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[receiver] = safeAdd(balances[receiver], tokens); emit Transfer(msg.sender, receiver, tokens); return true; }
2,116,577
[ 1, 29461, 12279, 326, 11013, 628, 1147, 3410, 1807, 2236, 358, 5971, 2236, 300, 16837, 1807, 2236, 1297, 1240, 18662, 11013, 358, 7412, 300, 374, 460, 29375, 854, 2935, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 12, 2867, 5971, 16, 2254, 2430, 13, 1071, 3849, 1135, 261, 6430, 2216, 13, 288, 203, 540, 203, 3639, 2583, 12, 24454, 480, 3474, 986, 93, 16, 315, 8496, 1554, 14266, 8214, 8863, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 4183, 1676, 12, 70, 26488, 63, 3576, 18, 15330, 6487, 2430, 1769, 203, 3639, 324, 26488, 63, 24454, 65, 273, 4183, 986, 12, 70, 26488, 63, 24454, 6487, 2430, 1769, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 5971, 16, 2430, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x94b34CcD6b6E39cF589d5be20B417e991FA86d1D/sources/contracts/GlobalsAndUtility.sol
1 CYAN = 1e12 CYANIDE
uint256 public constant CYANIDE_PER_CYAN = 1000000000000;
8,339,644
[ 1, 21, 29335, 1258, 273, 404, 73, 2138, 29335, 1258, 10385, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5381, 29335, 1258, 10385, 67, 3194, 67, 16068, 1258, 273, 15088, 9449, 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 ]
pragma solidity 0.8.11; /** * Wololo - a Moloch v2 mod that implements a DAO for the CEO of CryptoPunks (CIG) */ //import "./SafeMath.sol"; // solidity 0.8 does this contract Moloch { /*************** GLOBAL CONSTANTS ***************/ uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal uint256 public summoningTime; // needed to determine the current period address public depositToken; // deposit token contract reference; default = wETH // HARD-CODED LIMITS // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound uint256 constant MAX_NUMBER_OF_SHARES_AND_LOOT = 10**18; // maximum number of shares that can be minted uint256 constant MAX_TOKEN_WHITELIST_COUNT = 400; // maximum number of whitelisted tokens uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 200; // maximum number of tokens with non-zero balance in guildbank // *************** // EVENTS // *************** event SummonComplete( address indexed summoner, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward); event SubmitProposal( address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, ProposalAction action, uint256 proposalId, address indexed delegateKey, address indexed memberAddress); event SponsorProposal( address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod); event SubmitVote( uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote); event ProcessProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessWhitelistProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessGuildKickProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event Ragequit( address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn); event TokensCollected( address indexed token, uint256 amountToCollect); event CancelProposal( uint256 indexed proposalId, address applicantAddress); event UpdateDelegateKey( address indexed memberAddress, address newDelegateKey); event Withdraw( address indexed memberAddress, address token, uint256 amount); // ******************* // INTERNAL ACCOUNTING // ******************* struct Totals { uint256 proposalCount; // total proposals submitted uint256 totalShares; // total shares across all members uint256 totalLoot; // total loot across all members uint256 totalGuildBankTokens; // total tokens with non-zero balance in guild bank } Totals public totals; address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); mapping (address => mapping(address => uint256)) public userTokenBalances; // userTokenBalances[userAddress][tokenAddress] enum Vote { Null, // default value, counted as abstention Yes, No } enum ProposalAction { Join, GuildKick, // flags[5] Grant, Whitelist, // flags[4] Harvest, BuyCEO, SetPrice, RewardTarget, DepositTax, SetBaseUri } enum ProposalState { Proposed, Sponsored, // flags[0] Cancelled, // flags[3] Passed, // flags[2] Processed // flags[1] } struct Member { address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated uint256 shares; // the # of voting shares assigned to this member uint256 loot; // the loot amount available to this member (combined with shares on ragequit) bool exists; // always true once a member has been created uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on and sponsoring proposals } struct ProposalMutable { uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal ProposalState state; // processing state (it was in flags before) uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute address tributeToken; // tribute token contract reference uint256 paymentRequested; // amount of tokens requested as payment address paymentToken; // payment token contract reference uint256 startingPeriod; // the period in which voting can start for this proposal bytes32 details; // proposal details - could be IPFS hash, plaintext, or JSON ProposalAction action; // what action will the proposal do (it was recorded in flags before) } mapping (address => mapping(uint256 => Vote)) votesByMember; // the votes on each proposal by each member mapping(uint256 => ProposalMutable) public pState; // keeps variables that can mutate for a proposal mapping(address => bool) public tokenWhitelist; address[] public approvedTokens; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; mapping(uint256 => Proposal) public proposals; uint256[] public proposalQueue; modifier onlyMember { require(members[msg.sender].shares > 0 || members[msg.sender].loot > 0, "not a member"); _; } modifier onlyShareholder { require(members[msg.sender].shares > 0, "not a shareholder"); _; } modifier onlyDelegate { require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "not a delegate"); _; } constructor( address _summoner, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) { require(_summoner != address(0), "summoner cannot be 0"); require(_periodDuration > 0, "_periodDuration cannot be 0"); require(_votingPeriodLength > 0, "_votingPeriodLength cannot be 0"); require(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "_votingPeriodLength exceeds limit"); require(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "_gracePeriodLength exceeds limit"); require(_dilutionBound > 0, "_dilutionBound cannot be 0"); require(_dilutionBound <= MAX_DILUTION_BOUND, "_dilutionBound exceeds limit"); require(_approvedTokens.length > 0, "need at least one approved token"); require(_approvedTokens.length <= MAX_TOKEN_WHITELIST_COUNT, "too many tokens"); require(_proposalDeposit >= _processingReward, "_proposalDeposit cannot be smaller than _processingReward"); depositToken = _approvedTokens[0]; // NOTE: move event up here, avoid stack too deep if too many approved tokens emit SummonComplete(_summoner, _approvedTokens, block.timestamp, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward); for (uint256 i = 0; i < _approvedTokens.length; i++) { require(_approvedTokens[i] != address(0), "_approvedToken cannot be 0"); require(!tokenWhitelist[_approvedTokens[i]], "duplicate approved token"); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(_approvedTokens[i]); } periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; summoningTime = block.timestamp; members[_summoner] = Member(_summoner, 1, 0, true, 0, 0); memberAddressByDelegateKey[_summoner] = _summoner; totals.totalShares = 1; } /***************** PROPOSAL FUNCTIONS *****************/ function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details ) public returns (uint256 proposalId) { require(sharesRequested + lootRequested <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested"); require(tokenWhitelist[tributeToken], "tributeToken is not whitelisted"); require(tokenWhitelist[paymentToken], "payment is not whitelisted"); require(applicant != address(0), "applicant cannot be 0"); require(applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant address cannot be reserved"); require(members[applicant].jailed == 0, "proposal applicant must not be jailed"); if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) { require(totals.totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, 'cannot submit more tribute proposals for new tokens - guildbank is full'); } // collect tribute from proposer and store it in the Moloch until the proposal is processed require(IERC20(tributeToken).transferFrom(msg.sender, address(this), tributeOffered), "tribute token transfer failed"); unsafeAddToBalance(ESCROW, tributeToken, tributeOffered); ProposalAction action; if (paymentRequested > 0) { action = ProposalAction.Grant; } else { action = ProposalAction.Join; } _submitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, action); unchecked { return totals.proposalCount - 1; } } function submitWhitelistProposal(address tokenToWhitelist, bytes32 details) public returns (uint256 proposalId) { require(tokenToWhitelist != address(0), "must provide token address"); require(!tokenWhitelist[tokenToWhitelist], "cannot already have whitelisted the token"); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot submit more whitelist proposals"); ProposalAction action = ProposalAction.Whitelist; _submitProposal(address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, action); unchecked { return totals.proposalCount - 1; } } function submitGuildKickProposal(address memberToKick, bytes32 details) public returns (uint256 proposalId) { Member memory member = members[memberToKick]; require(member.shares > 0 || member.loot > 0, "member must have at least one share or one loot"); require(members[memberToKick].jailed == 0, "member must not already be jailed"); ProposalAction action = ProposalAction.GuildKick; _submitProposal(memberToKick, 0, 0, 0, address(0), 0, address(0), details, action); unchecked { return totals.proposalCount - 1; } } function _submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, ProposalAction action ) internal { Proposal storage p = proposals[totals.proposalCount]; p.applicant = applicant; p.proposer = msg.sender; //p.sponsor = address(0); p.sharesRequested = sharesRequested; p.lootRequested = lootRequested; p.tributeOffered = tributeOffered; p.tributeToken = tributeToken; p.paymentRequested = paymentRequested; p.paymentToken = paymentToken; //p.startingPeriod = 0; p.action = action; p.details = details; address memberAddress = memberAddressByDelegateKey[msg.sender]; // NOTE: argument order matters, avoid stack too deep emit SubmitProposal( applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, action, totals.proposalCount, msg.sender, memberAddress); unchecked { totals.proposalCount += 1; } } function sponsorProposal(uint256 proposalId) public onlyDelegate { // collect proposal deposit from sponsor and store it in the Moloch until the proposal is processed require(IERC20(depositToken).transferFrom(msg.sender, address(this), proposalDeposit), "proposal deposit token transfer failed"); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; require(proposal.proposer != address(0), 'proposal must have been proposed'); require(s.state == ProposalState.Proposed, "proposal not in proposed state"); require(members[proposal.applicant].jailed == 0, "proposal applicant must not be jailed"); if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) { require(totals.totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, 'cannot sponsor more tribute proposals for new tokens - guildbank is full'); } // whitelist proposal if (proposal.action == ProposalAction.Whitelist) { require(!tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token"); require(!proposedToWhitelist[address(proposal.tributeToken)], 'already proposed to whitelist'); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot sponsor more whitelist proposals"); proposedToWhitelist[address(proposal.tributeToken)] = true; // guild kick proposal } else if (proposal.action == ProposalAction.GuildKick) { require(!proposedToKick[proposal.applicant], 'already proposed to kick'); proposedToKick[proposal.applicant] = true; } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length - 1]].startingPeriod ) + 1; proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; s.state = ProposalState.Sponsored; // sponsored // append proposal to the queue proposalQueue.push(proposalId); emit SponsorProposal(msg.sender, memberAddress, proposalId, proposalQueue.length - 1, startingPeriod); } // NOTE: In MolochV2 proposalIndex !== proposalId function submitVote(uint256 proposalIndex, uint8 uintVote) public onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; Vote voteRecord = votesByMember[memberAddress][proposalIndex]; require(proposalIndex < proposalQueue.length, "proposal does not exist"); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; ProposalMutable storage s = pState[proposalQueue[proposalIndex]]; require(uintVote < 3, "must be less than 3"); Vote vote = Vote(uintVote); require(getCurrentPeriod() >= proposal.startingPeriod, "voting period has not started"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "proposal voting period has expired"); require(voteRecord == Vote.Null, "member has already voted"); require(vote == Vote.Yes || vote == Vote.No, "vote must be either Yes or No"); votesByMember[memberAddress][proposalIndex] = vote; if (vote == Vote.Yes) { s.yesVotes = s.yesVotes + member.shares; // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totals.totalShares + totals.totalLoot > s.maxTotalSharesAndLootAtYesVote) { s.maxTotalSharesAndLootAtYesVote = totals.totalShares + totals.totalLoot; } } else if (vote == Vote.No) { s.noVotes = s.noVotes + member.shares; } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set untill it's been sponsored but proposal is created on submission emit SubmitVote(proposalQueue[proposalIndex], proposalIndex, msg.sender, memberAddress, uintVote); } function processProposal(uint256 proposalIndex) public { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal memory proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; require( proposal.action == ProposalAction.Join || proposal.action == ProposalAction.Grant, "must be a standard proposal" ); s.state = ProposalState.Processed; // TODO unnecessary write bool didPass = _didPass(proposalIndex); // Make the proposal fail if the new total number of shares and loot exceeds the limit if (totals.totalShares + totals.totalLoot + proposal.sharesRequested + proposal.lootRequested > MAX_NUMBER_OF_SHARES_AND_LOOT) { didPass = false; } // Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance if (proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) { didPass = false; } // Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totals.totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT) { didPass = false; } // PROPOSAL PASSED if (didPass) { s.state = ProposalState.Passed; // if the applicant is already a member, add to their existing shares & loot if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares + proposal.sharesRequested; members[proposal.applicant].loot = members[proposal.applicant].loot + proposal.lootRequested; // the applicant is a new member, create a new record for them } else { // if the applicant address is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[proposal.applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[proposal.applicant]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } // use applicant address as delegateKey by default members[proposal.applicant] = Member(proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true, 0, 0); memberAddressByDelegateKey[proposal.applicant] = proposal.applicant; } // mint new shares & loot totals.totalShares = totals.totalShares + proposal.sharesRequested; totals.totalLoot = totals.totalLoot + proposal.lootRequested; // if the proposal tribute is the first tokens of its kind to make it into the guild bank, increment total guild bank tokens if (userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0) { unchecked { totals.totalGuildBankTokens += 1; } } unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered); unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested); // if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { unchecked { totals.totalGuildBankTokens -= 1; } } // PROPOSAL FAILED } else { // return all tokens to the proposer (not the applicant, because funds come from proposer) unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); } function processWhitelistProposal(uint256 proposalIndex) public { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal memory proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; require(proposal.action == ProposalAction.Whitelist, "must be a whitelist proposal"); // TODO optimize s.state so that we are not writing twice to it s.state = ProposalState.Processed; // processed bool didPass = _didPass(proposalIndex); if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) { didPass = false; } if (didPass) { s.state = ProposalState.Passed; // didPass tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); } proposedToWhitelist[address(proposal.tributeToken)] = false; _returnDeposit(proposal.sponsor); emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass); } function processGuildKickProposal(uint256 proposalIndex) public { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal memory proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; require(proposal.action == ProposalAction.GuildKick, "must be a guild kick proposal"); s.state = ProposalState.Processed; // processed bool didPass = _didPass(proposalIndex); if (didPass) { s.state = ProposalState.Passed; // didPass Member storage member = members[proposal.applicant]; member.jailed = proposalIndex; // transfer shares to loot member.loot = member.loot + member.shares; totals.totalShares = totals.totalShares - member.shares; totals.totalLoot = totals.totalLoot + member.shares; member.shares = 0; // revoke all shares } proposedToKick[proposal.applicant] = false; _returnDeposit(proposal.sponsor); emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass); } function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; ProposalMutable memory s = pState[proposalQueue[proposalIndex]]; didPass = s.yesVotes > s.noVotes; // Make the proposal fail if the dilutionBound is exceeded if ((totals.totalShares + (totals.totalLoot)) * (dilutionBound) < s.maxTotalSharesAndLootAtYesVote) { didPass = false; } // Make the proposal fail if the applicant is jailed // - for standard proposals, we don't want the applicant to get any shares/loot/payment // - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; } function _validateProposalForProcessing(uint256 proposalIndex) internal view { require(proposalIndex < proposalQueue.length, "proposal does not exist"); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; ProposalMutable memory s = pState[proposalQueue[proposalIndex]]; require(getCurrentPeriod() >= proposal.startingPeriod + votingPeriodLength + gracePeriodLength, "proposal is not ready to be processed" ); require(s.state != ProposalState.Processed, "proposal has already been processed"); require( proposalIndex == 0 || pState[proposalQueue[proposalIndex-1]].state == ProposalState.Processed, "previous proposal must be processed" ); } function _returnDeposit(address sponsor) internal { unsafeInternalTransfer(ESCROW, msg.sender, depositToken, processingReward); unsafeInternalTransfer(ESCROW, sponsor, depositToken, proposalDeposit - processingReward); } function ragequit(uint256 sharesToBurn, uint256 lootToBurn) external onlyMember { _ragequit(msg.sender, sharesToBurn, lootToBurn); } function _ragequit(address memberAddress, uint256 sharesToBurn, uint256 lootToBurn) internal { uint256 initialTotalSharesAndLoot = totals.totalShares + totals.totalLoot; Member storage member = members[memberAddress]; require(member.shares >= sharesToBurn, "insufficient shares"); require(member.loot >= lootToBurn, "insufficient loot"); require(canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed"); uint256 sharesAndLootToBurn = sharesToBurn + lootToBurn; // burn shares and loot member.shares = member.shares - sharesToBurn; member.loot = member.loot - lootToBurn; totals.totalShares = totals.totalShares - sharesToBurn; totals.totalLoot = totals.totalLoot - lootToBurn; for (uint256 i = 0; i < approvedTokens.length; i++) { uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways unchecked { userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit; userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit; } } } emit Ragequit(msg.sender, sharesToBurn, lootToBurn); } function ragekick(address memberToKick) public { Member storage member = members[memberToKick]; require(member.jailed != 0, "member must be in jail"); require(member.loot > 0, "member must have some loot"); // note - should be impossible for jailed member to have shares require(canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed"); _ragequit(memberToKick, 0, member.loot); } function withdrawBalance(address _token, uint256 _amount) public { _withdrawBalance(_token, _amount); } function withdrawBalances( address[] memory _tokens, uint256[] memory _amounts, bool _max) public { require(_tokens.length == _amounts.length, "tokens and amounts arrays must be matching lengths"); for (uint256 i=0; i < _tokens.length; i++) { uint256 withdrawAmount = _amounts[i]; if (_max) { // withdraw the maximum balance withdrawAmount = userTokenBalances[msg.sender][_tokens[i]]; } _withdrawBalance(_tokens[i], withdrawAmount); } } function _withdrawBalance(address token, uint256 amount) internal { require(userTokenBalances[msg.sender][token] >= amount, "insufficient balance"); unsafeSubtractFromBalance(msg.sender, token, amount); require(IERC20(token).transfer(msg.sender, amount), "transfer failed"); emit Withdraw(msg.sender, token, amount); } function collectTokens(address token) public onlyDelegate { uint256 amountToCollect = IERC20(token).balanceOf(address(this)) - userTokenBalances[TOTAL][token]; // only collect if 1) there are tokens to collect 2) token is whitelisted 3) token has non-zero balance require(amountToCollect > 0, 'no tokens to collect'); require(tokenWhitelist[token], 'token to collect must be whitelisted'); require(userTokenBalances[GUILD][token] > 0, 'token to collect must have non-zero guild bank balance'); unsafeAddToBalance(GUILD, token, amountToCollect); emit TokensCollected(token, amountToCollect); } // NOTE: requires that delegate key which sent the original proposal cancels, msg.sender == proposal.proposer function cancelProposal(uint256 proposalId) external { Proposal memory proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; //require(s.state != ProposalState.Sponsored, "proposal has already been sponsored"); //require(s.state != ProposalState.Cancelled, "proposal has already been cancelled"); require(s.state == ProposalState.Proposed, "must be in Proposed state"); require(msg.sender == proposal.proposer, "solely the proposer can cancel"); s.state = ProposalState.Cancelled; // cancelled unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) external onlyShareholder { require(newDelegateKey != address(0), "newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require(!members[newDelegateKey].exists, "cannot overwrite existing members"); require(!members[memberAddressByDelegateKey[newDelegateKey]].exists, "cannot overwrite existing delegate keys"); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { require(highestIndexYesVote < proposalQueue.length, "proposal does not exist"); return pState[proposalQueue[highestIndexYesVote]].state == ProposalState.Processed; } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= startingPeriod + votingPeriodLength; } /*************** GETTER FUNCTIONS ***************/ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return (block.timestamp - summoningTime) / periodDuration; } function getProposalQueueLength() public view returns (uint256) { return proposalQueue.length; } function getUserTokenBalance(address user, address token) public view returns (uint256) { return userTokenBalances[user][token]; } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) { require(members[memberAddress].exists, "member does not exist"); require(proposalIndex < proposalQueue.length, "proposal does not exist"); return votesByMember[memberAddress][proposalIndex]; } function getTokenCount() public view returns (uint256) { return approvedTokens.length; } /*************** HELPER FUNCTIONS ***************/ function unsafeAddToBalance(address user, address token, uint256 amount) internal { unchecked { userTokenBalances[user][token] += amount; userTokenBalances[TOTAL][token] += amount; } } function unsafeSubtractFromBalance(address user, address token, uint256 amount) internal { unchecked { userTokenBalances[user][token] -= amount; userTokenBalances[TOTAL][token] -= amount; } } function unsafeInternalTransfer(address from, address to, address token, uint256 amount) internal { unsafeSubtractFromBalance(from, token, amount); unsafeAddToBalance(to, token, amount); } function fairShare(uint256 balance, uint256 shares, uint256 totalShares) internal pure returns (uint256) { require(totalShares != 0); if (balance == 0) { return 0; } //uint256 prod = balance * shares; //if (prod / balance == shares) { // no overflow in multiplication above? (solidity 0.8 checks this) // return prod / totalShares; //} return (balance / totalShares) * shares; } } interface IERC20 { 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); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
collect proposal deposit from sponsor and store it in the Moloch until the proposal is processed whitelist proposal guild kick proposal
function sponsorProposal(uint256 proposalId) public onlyDelegate { require(IERC20(depositToken).transferFrom(msg.sender, address(this), proposalDeposit), "proposal deposit token transfer failed"); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; require(proposal.proposer != address(0), 'proposal must have been proposed'); require(s.state == ProposalState.Proposed, "proposal not in proposed state"); require(members[proposal.applicant].jailed == 0, "proposal applicant must not be jailed"); if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) { require(totals.totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, 'cannot sponsor more tribute proposals for new tokens - guildbank is full'); } if (proposal.action == ProposalAction.Whitelist) { require(!tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token"); require(!proposedToWhitelist[address(proposal.tributeToken)], 'already proposed to whitelist'); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot sponsor more whitelist proposals"); proposedToWhitelist[address(proposal.tributeToken)] = true; require(!proposedToKick[proposal.applicant], 'already proposed to kick'); proposedToKick[proposal.applicant] = true; } getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length - 1]].startingPeriod ) + 1; proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; emit SponsorProposal(msg.sender, memberAddress, proposalId, proposalQueue.length - 1, startingPeriod); }
2,544,182
[ 1, 14676, 14708, 443, 1724, 628, 272, 500, 2467, 471, 1707, 518, 316, 326, 490, 355, 9842, 3180, 326, 14708, 353, 5204, 10734, 14708, 15488, 23228, 14708, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 272, 500, 2467, 14592, 12, 11890, 5034, 14708, 548, 13, 1071, 1338, 9586, 288, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 323, 1724, 1345, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 14708, 758, 1724, 3631, 315, 685, 8016, 443, 1724, 1147, 7412, 2535, 8863, 203, 3639, 7127, 986, 774, 13937, 12, 41, 2312, 11226, 16, 443, 1724, 1345, 16, 14708, 758, 1724, 1769, 203, 203, 3639, 19945, 2502, 14708, 273, 450, 22536, 63, 685, 8016, 548, 15533, 203, 3639, 19945, 19536, 2502, 272, 273, 293, 1119, 63, 685, 8016, 548, 15533, 203, 203, 3639, 2583, 12, 685, 8016, 18, 685, 5607, 480, 1758, 12, 20, 3631, 296, 685, 8016, 1297, 1240, 2118, 20084, 8284, 203, 3639, 2583, 12, 87, 18, 2019, 422, 19945, 1119, 18, 626, 7423, 16, 315, 685, 8016, 486, 316, 20084, 919, 8863, 203, 203, 3639, 2583, 12, 7640, 63, 685, 8016, 18, 438, 1780, 970, 8009, 78, 1708, 422, 374, 16, 315, 685, 8016, 513, 1780, 970, 1297, 486, 506, 525, 1708, 8863, 203, 203, 3639, 309, 261, 685, 8016, 18, 887, 10513, 329, 405, 374, 597, 729, 1345, 38, 26488, 63, 30673, 11382, 6362, 685, 8016, 18, 887, 1345, 65, 422, 374, 13, 288, 203, 5411, 2583, 12, 3307, 1031, 18, 4963, 43, 680, 16040, 5157, 411, 4552, 67, 8412, 67, 30673, 2627, 2290, 20201, 67, 7240, 16, 296, 12892, 272, 500, 2467, 1898, 433, 495, 624, 450, 22536, 364, 394, 2430, 300, 15488, 10546, 353, 1983, 8284, 203, 3639, 2 ]
./partial_match/3/0x324b3EB5B419Cb3a1fa2eFd6Ac778aA84bf6D673/sources/SeekGold.sol
* Withdraws all of the callers earnings./ setup data update dividend tracker add ref. bonus delivery service fire event
function withdraw() onlyhodler() public userCheck contractLockCheck{ address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += (referralBalance_[_customerAddress] + directBonusBalance[_customerAddress]); referralBalance_[_customerAddress] = 0; directBonusBalance[_customerAddress] = 0; address(uint160(_customerAddress)).transfer(_dividends); emit onWithdraw(_customerAddress, _dividends); }
5,341,153
[ 1, 1190, 9446, 87, 777, 434, 326, 19932, 425, 1303, 899, 18, 19, 3875, 501, 1089, 31945, 9745, 527, 1278, 18, 324, 22889, 7912, 1156, 4452, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 1435, 1338, 76, 369, 749, 1435, 1071, 729, 1564, 6835, 2531, 1564, 95, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 293, 2012, 11634, 67, 63, 67, 10061, 1887, 65, 1011, 225, 261, 474, 5034, 13, 261, 67, 2892, 350, 5839, 380, 13463, 1769, 203, 540, 203, 3639, 389, 2892, 350, 5839, 1011, 261, 1734, 29084, 13937, 67, 63, 67, 10061, 1887, 65, 397, 2657, 38, 22889, 13937, 63, 67, 10061, 1887, 19226, 203, 3639, 1278, 29084, 13937, 67, 63, 67, 10061, 1887, 65, 273, 374, 31, 203, 3639, 2657, 38, 22889, 13937, 63, 67, 10061, 1887, 65, 273, 374, 31, 203, 540, 203, 3639, 1758, 12, 11890, 16874, 24899, 10061, 1887, 13, 2934, 13866, 24899, 2892, 350, 5839, 1769, 203, 540, 203, 3639, 3626, 603, 1190, 9446, 24899, 10061, 1887, 16, 389, 2892, 350, 5839, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 2019 Sean Thoman 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; import "@0x/contracts-utils/contracts/utils/LibBytes/LibBytes.sol"; import "@0x/contracts-utils/contracts/utils/Ownable/Ownable.sol"; import "./ECRecover.sol"; // Sealed commit reveal scheme for sealed bid auctions. This contract // is solely responsible for receiving hashed bid commitments during // the commit phase of the auction, and receiving the revealed amount // during the reveal phase. It does not determine the highest bidder // but anyone should be able to examine the results of this contract // to contest the winner. contract SealedCR is ECRecover, Ownable { using LibBytes for bytes; // struct Bid { address auctionContract; // the auction contract this bid is for address signerAddr; // the signing address of the bid sender, for state channel address bidderAddr; // the transactional address of the bid sender address revealAddr; // the address of the bid revealer, should match the signer bytes32 revealHash; // the hash from the reveal operation uint256 revealAmount; // the clear bid value bytes commitSignature; // signature of the bid sender } // mapping of commit hash to bid object mapping(bytes32 => Bid) public bids; // mapping of main address to address with signing permission mapping(address => address) public signers; // event Reveal(address bidderAddress, uint256 amount); // Register with the contract, TODO: think about this as KYC/Identity entry point function register(address signerAddress) public { signers[signerAddress] = msg.sender; } // Add a commitment, also known as a bid in this auction. Each bid // is hashed by the bidder before submitting to this function. The // hash can be validated during a challenge by ecrecover. // function commit(bytes32 commitHash, bytes memory signature, address auctionContract) public //onlyOwner { address signerAddress = ecr(commitHash, signature); require( signerAddress != address(0), "ECRECOVER_FAILED" ); address bidderAddress = signers[signerAddress]; bids[commitHash] = Bid(auctionContract, signerAddress, bidderAddress, address(0), 0, 0, signature); } // Reveal the salt used to hash each bid as well as the actual bid // amount after the auction is closed. This is analogous to opening // a sealed envelope containing each bidders' bid amount. function reveal(uint256 revealAmount, string salt) public //onlyOwner() { // Revealing a commitment to a previous bid requires the sender // to provide their random salt and the actual bid amount. bytes32 revealHash = keccak256(abi.encodePacked(revealAmount, salt)); require( bids[revealHash].signerAddr != address(0), "REVEAL_HASH_FAILED" ); bids[revealHash].revealHash = revealHash; bids[revealHash].revealAmount = revealAmount; // Reveal the sender & what they revealed, to anyone who needs // to examine the real price. emit Reveal(bids[revealHash].signerAddr, revealAmount); } // Since reveal() gave this contract the true bid amounts, now any // off chain process can compute the highest bid without incurring // any gas fees. Whomever computes the highest bid shall sign their // decision. Anyone can challenge the decision using this function // if it turns out the bid commitment address DOES NOT match the // revealers address. // // This is purposely the only function that is not marked onlyOwner() // function challenge(uint256 revealAmount, string salt, bytes memory signature) public { // bytes32 commitSignature = signature; bytes32 revealHash = keccak256(abi.encodePacked(revealAmount, salt)); address revealAddress = ecr(revealHash, signature); // require( // bids[revealHash].commitSignature == commitSignature, // "CHALLENGE_FAILED_BAD_SIGNATURE" // ); require( bids[revealHash].signerAddr != revealAddress, "CHALLENGE_FAILED" ); bids[revealHash].revealAddr = revealAddress; // CONSEQUENCE? } }
the clear bid value
uint256 revealAmount;
5,491,392
[ 1, 5787, 2424, 9949, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 2254, 5034, 283, 24293, 6275, 31, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x43949399D34f8B61a899581575b5259B36F418d0/sources/contracts/staking/VeBids.sol
@dev explicitly override multiple inheritance
function totalSupply() public view override(VeERC20,IVeBids) returns (uint256) { return super.totalSupply(); }
16,446,116
[ 1, 16511, 715, 3849, 3229, 16334, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 12, 58, 73, 654, 39, 3462, 16, 8188, 73, 38, 2232, 13, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 2240, 18, 4963, 3088, 1283, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/77/0x804A40d12FdeD71D41cD69a0054d371a80Cc84da/sources/deploy/contracts/synthereum-pool/v5/LiquidityPoolLib.sol
* @notice Returns if position is overcollateralized and thepercentage of coverage of the collateral according to the last price @param self Data type the library is attached to @param lpPosition Position of the LP (see LPPosition struct) @param liquidationData Liquidation info (see LiquidationData struct) @return True if position is overcollaterlized, otherwise false + percentage of coverage (totalCollateralAmount / (price tokensCollateralized))/
function collateralCoverage( ISynthereumLiquidityPoolStorage.Storage storage self, ISynthereumLiquidityPoolStorage.LPPosition storage lpPosition, ISynthereumLiquidityPoolStorage.Liquidation storage liquidationData ) external view returns (bool, uint256) { FixedPoint.Unsigned memory priceRate = getPriceFeedRate(self.finder, self.priceIdentifier); uint8 collateralDecimals = getCollateralDecimals(self.collateralToken); (bool _isOverCollateralized, ) = lpPosition.isOverCollateralized( liquidationData, priceRate, collateralDecimals, lpPosition.totalCollateralAmount ); FixedPoint.Unsigned memory _collateralCoverage = lpPosition.totalCollateralAmount.div( calculateCollateralAmount( priceRate, collateralDecimals, lpPosition.tokensCollateralized ) ); return (_isOverCollateralized, _collateralCoverage.rawValue); }
5,046,527
[ 1, 1356, 309, 1754, 353, 1879, 12910, 2045, 287, 1235, 471, 326, 18687, 434, 11196, 434, 326, 4508, 2045, 287, 4888, 358, 326, 1142, 6205, 225, 365, 1910, 618, 326, 5313, 353, 7495, 358, 225, 12423, 2555, 11010, 434, 326, 511, 52, 261, 5946, 511, 52, 2555, 1958, 13, 225, 4501, 26595, 367, 751, 511, 18988, 350, 367, 1123, 261, 5946, 511, 18988, 350, 367, 751, 1958, 13, 327, 1053, 309, 1754, 353, 1879, 12910, 2045, 80, 1235, 16, 3541, 629, 397, 11622, 434, 11196, 261, 4963, 13535, 2045, 287, 6275, 342, 261, 8694, 225, 2430, 13535, 2045, 287, 1235, 3719, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 4508, 2045, 287, 9739, 12, 203, 565, 4437, 878, 18664, 379, 48, 18988, 24237, 2864, 3245, 18, 3245, 2502, 365, 16, 203, 565, 4437, 878, 18664, 379, 48, 18988, 24237, 2864, 3245, 18, 14461, 2555, 2502, 12423, 2555, 16, 203, 565, 4437, 878, 18664, 379, 48, 18988, 24237, 2864, 3245, 18, 48, 18988, 350, 367, 2502, 4501, 26595, 367, 751, 203, 225, 262, 3903, 1476, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 565, 15038, 2148, 18, 13290, 3778, 6205, 4727, 273, 203, 1377, 25930, 8141, 4727, 12, 2890, 18, 15356, 16, 365, 18, 8694, 3004, 1769, 203, 203, 565, 2254, 28, 4508, 2045, 287, 31809, 273, 336, 13535, 2045, 287, 31809, 12, 2890, 18, 12910, 2045, 287, 1345, 1769, 203, 203, 565, 261, 6430, 389, 291, 4851, 13535, 2045, 287, 1235, 16, 262, 273, 203, 1377, 12423, 2555, 18, 291, 4851, 13535, 2045, 287, 1235, 12, 203, 3639, 4501, 26595, 367, 751, 16, 203, 3639, 6205, 4727, 16, 203, 3639, 4508, 2045, 287, 31809, 16, 203, 3639, 12423, 2555, 18, 4963, 13535, 2045, 287, 6275, 203, 1377, 11272, 203, 203, 565, 15038, 2148, 18, 13290, 3778, 389, 12910, 2045, 287, 9739, 273, 203, 1377, 12423, 2555, 18, 4963, 13535, 2045, 287, 6275, 18, 2892, 12, 203, 3639, 4604, 13535, 2045, 287, 6275, 12, 203, 1850, 6205, 4727, 16, 203, 1850, 4508, 2045, 287, 31809, 16, 203, 1850, 12423, 2555, 18, 7860, 13535, 2045, 287, 1235, 203, 3639, 262, 203, 1377, 11272, 203, 203, 565, 327, 261, 67, 291, 4851, 13535, 2 ]
pragma solidity >=0.5.13; import "./Avatar.sol"; import "../globalConstraints/GlobalConstraintInterface.sol"; /** * @title Controller contract * @dev A controller controls the organizations tokens, reputation and avatar. * It is subject to a set of schemes and constraints that determine its behavior. * Each scheme has it own parameters and operation permissions. */ contract Controller { struct Scheme { bytes32 paramsHash; // a hash "configuration" of the scheme bytes4 permissions; // A bitwise flags of permissions, // All 0: Not registered, // 1st bit: Flag if the scheme is registered, // 2nd bit: Scheme can register other schemes // 3rd bit: Scheme can add/remove global constraints // 4th bit: Scheme can upgrade the controller // 5th bit: Scheme can call genericCall on behalf of // the organization avatar } struct GlobalConstraint { address gcAddress; bytes32 params; } struct GlobalConstraintRegister { bool isRegistered; //is registered uint256 index; //index at globalConstraints } mapping(address=>Scheme) public schemes; Avatar public avatar; DAOToken public nativeToken; Reputation public nativeReputation; // newController will point to the new controller after the present controller is upgraded address public newController; // globalConstraintsPre that determine pre conditions for all actions on the controller GlobalConstraint[] public globalConstraintsPre; // globalConstraintsPost that determine post conditions for all actions on the controller GlobalConstraint[] public globalConstraintsPost; // globalConstraintsRegisterPre indicate if a globalConstraints is registered as a pre global constraint mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre; // globalConstraintsRegisterPost indicate if a globalConstraints is registered as a post global constraint mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPost; event MintReputation (address indexed _sender, address indexed _to, uint256 _amount); event BurnReputation (address indexed _sender, address indexed _from, uint256 _amount); event MintTokens (address indexed _sender, address indexed _beneficiary, uint256 _amount); event RegisterScheme (address indexed _sender, address indexed _scheme); event UnregisterScheme (address indexed _sender, address indexed _scheme); event UpgradeController(address indexed _oldController, address _newController); event AddGlobalConstraint( address indexed _globalConstraint, bytes32 _params, GlobalConstraintInterface.CallPhase _when); event RemoveGlobalConstraint(address indexed _globalConstraint, uint256 _index, bool _isPre); constructor( Avatar _avatar) public { avatar = _avatar; nativeToken = avatar.nativeToken(); nativeReputation = avatar.nativeReputation(); schemes[msg.sender] = Scheme({paramsHash: bytes32(0), permissions: bytes4(0x0000001F)}); emit RegisterScheme (msg.sender, msg.sender); } // Do not allow mistaken calls: // solhint-disable-next-line payable-fallback function() external { revert(); } // Modifiers: modifier onlyRegisteredScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000001) == bytes4(0x00000001)); _; } modifier onlyRegisteringSchemes() { require(schemes[msg.sender].permissions&bytes4(0x00000002) == bytes4(0x00000002)); _; } modifier onlyGlobalConstraintsScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000004) == bytes4(0x00000004)); _; } modifier onlyUpgradingScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000008) == bytes4(0x00000008)); _; } modifier onlyGenericCallScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000010) == bytes4(0x00000010)); _; } modifier onlyMetaDataScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000010) == bytes4(0x00000010)); _; } modifier onlySubjectToConstraint(bytes32 func) { uint256 idx; for (idx = 0; idx < globalConstraintsPre.length; idx++) { require( (GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress)) .pre(msg.sender, globalConstraintsPre[idx].params, func)); } _; for (idx = 0; idx < globalConstraintsPost.length; idx++) { require( (GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress)) .post(msg.sender, globalConstraintsPost[idx].params, func)); } } modifier isAvatarValid(address _avatar) { require(_avatar == address(avatar)); _; } /** * @dev Mint `_amount` of reputation that are assigned to `_to` . * @param _amount amount of reputation to mint * @param _to beneficiary address * @return bool which represents a success */ function mintReputation(uint256 _amount, address _to, address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("mintReputation") isAvatarValid(_avatar) returns(bool) { emit MintReputation(msg.sender, _to, _amount); return nativeReputation.mint(_to, _amount); } /** * @dev Burns `_amount` of reputation from `_from` * @param _amount amount of reputation to burn * @param _from The address that will lose the reputation * @return bool which represents a success */ function burnReputation(uint256 _amount, address _from, address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("burnReputation") isAvatarValid(_avatar) returns(bool) { emit BurnReputation(msg.sender, _from, _amount); return nativeReputation.burn(_from, _amount); } /** * @dev mint tokens . * @param _amount amount of token to mint * @param _beneficiary beneficiary address * @return bool which represents a success */ function mintTokens(uint256 _amount, address _beneficiary, address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("mintTokens") isAvatarValid(_avatar) returns(bool) { emit MintTokens(msg.sender, _beneficiary, _amount); return nativeToken.mint(_beneficiary, _amount); } /** * @dev register a scheme * @param _scheme the address of the scheme * @param _paramsHash a hashed configuration of the usage of the scheme * @param _permissions the permissions the new scheme will have * @return bool which represents a success */ function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) external onlyRegisteringSchemes onlySubjectToConstraint("registerScheme") isAvatarValid(_avatar) returns(bool) { Scheme memory scheme = schemes[_scheme]; // Check scheme has at least the permissions it is changing, and at least the current permissions: // Implementation is a bit messy. One must recall logic-circuits ^^ // produces non-zero if sender does not have all of the perms that are changing between old and new require(bytes4(0x0000001f)&(_permissions^scheme.permissions)&(~schemes[msg.sender].permissions) == bytes4(0)); // produces non-zero if sender does not have all of the perms in the old scheme require(bytes4(0x0000001f)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0)); // Add or change the scheme: schemes[_scheme].paramsHash = _paramsHash; schemes[_scheme].permissions = _permissions|bytes4(0x00000001); emit RegisterScheme(msg.sender, _scheme); return true; } /** * @dev unregister a scheme * @param _scheme the address of the scheme * @return bool which represents a success */ function unregisterScheme( address _scheme, address _avatar) external onlyRegisteringSchemes onlySubjectToConstraint("unregisterScheme") isAvatarValid(_avatar) returns(bool) { //check if the scheme is registered if (_isSchemeRegistered(_scheme) == false) { return false; } // Check the unregistering scheme has enough permissions: require(bytes4(0x0000001f)&(schemes[_scheme].permissions&(~schemes[msg.sender].permissions)) == bytes4(0)); // Unregister: emit UnregisterScheme(msg.sender, _scheme); delete schemes[_scheme]; return true; } /** * @dev unregister the caller's scheme * @return bool which represents a success */ function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) { if (_isSchemeRegistered(msg.sender) == false) { return false; } delete schemes[msg.sender]; emit UnregisterScheme(msg.sender, msg.sender); return true; } /** * @dev add or update Global Constraint * @param _globalConstraint the address of the global constraint to be added. * @param _params the constraint parameters hash. * @return bool which represents a success */ function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) { globalConstraintsPre.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPre.length-1); }else { globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) { globalConstraintsPost.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPost.length-1); }else { globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params; } } emit AddGlobalConstraint(_globalConstraint, _params, when); return true; } /** * @dev remove Global Constraint * @param _globalConstraint the address of the global constraint to be remove. * @return bool which represents a success */ // solhint-disable-next-line code-complexity function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint( _globalConstraint, globalConstraintRegister.index, when == GlobalConstraintInterface.CallPhase.Pre ); } return retVal; } /** * @dev upgrade the Controller * The function will trigger an event 'UpgradeController'. * @param _newController the address of the new controller. * @return bool which represents a success */ function upgradeController(address _newController, Avatar _avatar) external onlyUpgradingScheme isAvatarValid(address(_avatar)) returns(bool) { require(newController == address(0)); // so the upgrade could be done once for a contract. require(_newController != address(0)); newController = _newController; avatar.transferOwnership(_newController); require(avatar.owner() == _newController); if (nativeToken.owner() == address(this)) { nativeToken.transferOwnership(_newController); require(nativeToken.owner() == _newController); } if (nativeReputation.owner() == address(this)) { nativeReputation.transferOwnership(_newController); require(nativeReputation.owner() == _newController); } emit UpgradeController(address(this), newController); return true; } /** * @dev perform a generic call to an arbitrary contract * @param _contract the contract's address to call * @param _data ABI-encoded contract call to call `_contract` address. * @param _avatar the controller's avatar address * @param _value value (ETH) to transfer with the transaction * @return bool -success * bytes - the return value of the called _contract's function. */ function genericCall(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value) external onlyGenericCallScheme onlySubjectToConstraint("genericCall") isAvatarValid(address(_avatar)) returns (bool, bytes memory) { return avatar.genericCall(_contract, _data, _value); } /** * @dev send some ether * @param _amountInWei the amount of ether (in Wei) to send * @param _to address of the beneficiary * @return bool which represents a success */ function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar) external onlyRegisteredScheme onlySubjectToConstraint("sendEther") isAvatarValid(address(_avatar)) returns(bool) { return avatar.sendEther(_amountInWei, _to); } /** * @dev send some amount of arbitrary ERC20 Tokens * @param _externalToken the address of the Token Contract * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @return bool which represents a success */ function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenTransfer") isAvatarValid(address(_avatar)) returns(bool) { return avatar.externalTokenTransfer(_externalToken, _to, _value); } /** * @dev transfer token "from" address "to" address * One must to approve the amount of tokens which can be spend from the * "from" account.This can be done using externalTokenApprove. * @param _externalToken the address of the Token Contract * @param _from address of the account to send from * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @return bool which represents a success */ function externalTokenTransferFrom( IERC20 _externalToken, address _from, address _to, uint256 _value, Avatar _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenTransferFrom") isAvatarValid(address(_avatar)) returns(bool) { return avatar.externalTokenTransferFrom(_externalToken, _from, _to, _value); } /** * @dev externalTokenApproval approve the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _value the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenIncreaseApproval") isAvatarValid(address(_avatar)) returns(bool) { return avatar.externalTokenApproval(_externalToken, _spender, _value); } /** * @dev metaData emits an event with a string, should contain the hash of some meta data. * @param _metaData a string representing a hash of the meta data * @param _avatar Avatar * @return bool which represents a success */ function metaData(string calldata _metaData, Avatar _avatar) external onlyMetaDataScheme isAvatarValid(address(_avatar)) returns(bool) { return avatar.metaData(_metaData); } /** * @dev getNativeReputation * @param _avatar the organization avatar. * @return organization native reputation */ function getNativeReputation(address _avatar) external isAvatarValid(_avatar) view returns(address) { return address(nativeReputation); } function isSchemeRegistered(address _scheme, address _avatar) external isAvatarValid(_avatar) view returns(bool) { return _isSchemeRegistered(_scheme); } function getSchemeParameters(address _scheme, address _avatar) external isAvatarValid(_avatar) view returns(bytes32) { return schemes[_scheme].paramsHash; } function getSchemePermissions(address _scheme, address _avatar) external isAvatarValid(_avatar) view returns(bytes4) { return schemes[_scheme].permissions; } function getGlobalConstraintParameters(address _globalConstraint, address) external view returns(bytes32) { GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPre[register.index].params; } register = globalConstraintsRegisterPost[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPost[register.index].params; } } /** * @dev globalConstraintsCount return the global constraint pre and post count * @return uint256 globalConstraintsPre count. * @return uint256 globalConstraintsPost count. */ function globalConstraintsCount(address _avatar) external isAvatarValid(_avatar) view returns(uint, uint) { return (globalConstraintsPre.length, globalConstraintsPost.length); } function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external isAvatarValid(_avatar) view returns(bool) { return (globalConstraintsRegisterPre[_globalConstraint].isRegistered || globalConstraintsRegisterPost[_globalConstraint].isRegistered); } function _isSchemeRegistered(address _scheme) private view returns(bool) { return (schemes[_scheme].permissions&bytes4(0x00000001) != bytes4(0)); } }
* @title Controller contract @dev A controller controls the organizations tokens, reputation and avatar. It is subject to a set of schemes and constraints that determine its behavior. Each scheme has it own parameters and operation permissions./
contract Controller { struct Scheme { } struct GlobalConstraint { address gcAddress; bytes32 params; } struct GlobalConstraintRegister { } mapping(address=>Scheme) public schemes; Avatar public avatar; DAOToken public nativeToken; Reputation public nativeReputation; GlobalConstraint[] public globalConstraintsPre; event MintReputation (address indexed _sender, address indexed _to, uint256 _amount); event BurnReputation (address indexed _sender, address indexed _from, uint256 _amount); event MintTokens (address indexed _sender, address indexed _beneficiary, uint256 _amount); event RegisterScheme (address indexed _sender, address indexed _scheme); event UnregisterScheme (address indexed _sender, address indexed _scheme); event UpgradeController(address indexed _oldController, address _newController); event AddGlobalConstraint( address indexed _globalConstraint, bytes32 _params, GlobalConstraintInterface.CallPhase _when); event RemoveGlobalConstraint(address indexed _globalConstraint, uint256 _index, bool _isPre); address public newController; GlobalConstraint[] public globalConstraintsPost; mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre; mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPost; constructor( Avatar _avatar) public { avatar = _avatar; nativeToken = avatar.nativeToken(); nativeReputation = avatar.nativeReputation(); emit RegisterScheme (msg.sender, msg.sender); } schemes[msg.sender] = Scheme({paramsHash: bytes32(0), permissions: bytes4(0x0000001F)}); function() external { revert(); } modifier onlyRegisteredScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000001) == bytes4(0x00000001)); _; } modifier onlyRegisteringSchemes() { require(schemes[msg.sender].permissions&bytes4(0x00000002) == bytes4(0x00000002)); _; } modifier onlyGlobalConstraintsScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000004) == bytes4(0x00000004)); _; } modifier onlyUpgradingScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000008) == bytes4(0x00000008)); _; } modifier onlyGenericCallScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000010) == bytes4(0x00000010)); _; } modifier onlyMetaDataScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000010) == bytes4(0x00000010)); _; } modifier onlySubjectToConstraint(bytes32 func) { uint256 idx; for (idx = 0; idx < globalConstraintsPre.length; idx++) { require( (GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress)) .pre(msg.sender, globalConstraintsPre[idx].params, func)); } _; for (idx = 0; idx < globalConstraintsPost.length; idx++) { require( (GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress)) .post(msg.sender, globalConstraintsPost[idx].params, func)); } } modifier onlySubjectToConstraint(bytes32 func) { uint256 idx; for (idx = 0; idx < globalConstraintsPre.length; idx++) { require( (GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress)) .pre(msg.sender, globalConstraintsPre[idx].params, func)); } _; for (idx = 0; idx < globalConstraintsPost.length; idx++) { require( (GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress)) .post(msg.sender, globalConstraintsPost[idx].params, func)); } } modifier onlySubjectToConstraint(bytes32 func) { uint256 idx; for (idx = 0; idx < globalConstraintsPre.length; idx++) { require( (GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress)) .pre(msg.sender, globalConstraintsPre[idx].params, func)); } _; for (idx = 0; idx < globalConstraintsPost.length; idx++) { require( (GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress)) .post(msg.sender, globalConstraintsPost[idx].params, func)); } } modifier isAvatarValid(address _avatar) { require(_avatar == address(avatar)); _; } function mintReputation(uint256 _amount, address _to, address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("mintReputation") isAvatarValid(_avatar) returns(bool) { emit MintReputation(msg.sender, _to, _amount); return nativeReputation.mint(_to, _amount); } function burnReputation(uint256 _amount, address _from, address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("burnReputation") isAvatarValid(_avatar) returns(bool) { emit BurnReputation(msg.sender, _from, _amount); return nativeReputation.burn(_from, _amount); } function mintTokens(uint256 _amount, address _beneficiary, address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("mintTokens") isAvatarValid(_avatar) returns(bool) { emit MintTokens(msg.sender, _beneficiary, _amount); return nativeToken.mint(_beneficiary, _amount); } function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) external onlyRegisteringSchemes onlySubjectToConstraint("registerScheme") isAvatarValid(_avatar) returns(bool) { Scheme memory scheme = schemes[_scheme]; require(bytes4(0x0000001f)&(_permissions^scheme.permissions)&(~schemes[msg.sender].permissions) == bytes4(0)); require(bytes4(0x0000001f)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0)); schemes[_scheme].paramsHash = _paramsHash; schemes[_scheme].permissions = _permissions|bytes4(0x00000001); emit RegisterScheme(msg.sender, _scheme); return true; } function unregisterScheme( address _scheme, address _avatar) external onlyRegisteringSchemes onlySubjectToConstraint("unregisterScheme") isAvatarValid(_avatar) returns(bool) { if (_isSchemeRegistered(_scheme) == false) { return false; } delete schemes[_scheme]; return true; } function unregisterScheme( address _scheme, address _avatar) external onlyRegisteringSchemes onlySubjectToConstraint("unregisterScheme") isAvatarValid(_avatar) returns(bool) { if (_isSchemeRegistered(_scheme) == false) { return false; } delete schemes[_scheme]; return true; } require(bytes4(0x0000001f)&(schemes[_scheme].permissions&(~schemes[msg.sender].permissions)) == bytes4(0)); emit UnregisterScheme(msg.sender, _scheme); function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) { if (_isSchemeRegistered(msg.sender) == false) { return false; } delete schemes[msg.sender]; emit UnregisterScheme(msg.sender, msg.sender); return true; } function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) { if (_isSchemeRegistered(msg.sender) == false) { return false; } delete schemes[msg.sender]; emit UnregisterScheme(msg.sender, msg.sender); return true; } function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) { globalConstraintsPre.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPre.length-1); globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) { globalConstraintsPost.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPost.length-1); globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params; } } emit AddGlobalConstraint(_globalConstraint, _params, when); return true; } function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) { globalConstraintsPre.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPre.length-1); globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) { globalConstraintsPost.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPost.length-1); globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params; } } emit AddGlobalConstraint(_globalConstraint, _params, when); return true; } function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) { globalConstraintsPre.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPre.length-1); globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) { globalConstraintsPost.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPost.length-1); globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params; } } emit AddGlobalConstraint(_globalConstraint, _params, when); return true; } }else { function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) { globalConstraintsPre.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPre.length-1); globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) { globalConstraintsPost.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPost.length-1); globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params; } } emit AddGlobalConstraint(_globalConstraint, _params, when); return true; } function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) { globalConstraintsPre.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPre.length-1); globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) { globalConstraintsPost.push(GlobalConstraint(_globalConstraint, _params)); globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true, globalConstraintsPost.length-1); globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params; } } emit AddGlobalConstraint(_globalConstraint, _params, when); return true; } }else { function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint( _globalConstraint, globalConstraintRegister.index, when == GlobalConstraintInterface.CallPhase.Pre ); } return retVal; } function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint( _globalConstraint, globalConstraintRegister.index, when == GlobalConstraintInterface.CallPhase.Pre ); } return retVal; } function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint( _globalConstraint, globalConstraintRegister.index, when == GlobalConstraintInterface.CallPhase.Pre ); } return retVal; } function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint( _globalConstraint, globalConstraintRegister.index, when == GlobalConstraintInterface.CallPhase.Pre ); } return retVal; } function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint( _globalConstraint, globalConstraintRegister.index, when == GlobalConstraintInterface.CallPhase.Pre ); } return retVal; } function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint( _globalConstraint, globalConstraintRegister.index, when == GlobalConstraintInterface.CallPhase.Pre ); } return retVal; } function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint( _globalConstraint, globalConstraintRegister.index, when == GlobalConstraintInterface.CallPhase.Pre ); } return retVal; } function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)|| (when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint( _globalConstraint, globalConstraintRegister.index, when == GlobalConstraintInterface.CallPhase.Pre ); } return retVal; } function upgradeController(address _newController, Avatar _avatar) external onlyUpgradingScheme isAvatarValid(address(_avatar)) returns(bool) { require(_newController != address(0)); newController = _newController; avatar.transferOwnership(_newController); require(avatar.owner() == _newController); if (nativeToken.owner() == address(this)) { nativeToken.transferOwnership(_newController); require(nativeToken.owner() == _newController); } if (nativeReputation.owner() == address(this)) { nativeReputation.transferOwnership(_newController); require(nativeReputation.owner() == _newController); } emit UpgradeController(address(this), newController); return true; } function upgradeController(address _newController, Avatar _avatar) external onlyUpgradingScheme isAvatarValid(address(_avatar)) returns(bool) { require(_newController != address(0)); newController = _newController; avatar.transferOwnership(_newController); require(avatar.owner() == _newController); if (nativeToken.owner() == address(this)) { nativeToken.transferOwnership(_newController); require(nativeToken.owner() == _newController); } if (nativeReputation.owner() == address(this)) { nativeReputation.transferOwnership(_newController); require(nativeReputation.owner() == _newController); } emit UpgradeController(address(this), newController); return true; } function upgradeController(address _newController, Avatar _avatar) external onlyUpgradingScheme isAvatarValid(address(_avatar)) returns(bool) { require(_newController != address(0)); newController = _newController; avatar.transferOwnership(_newController); require(avatar.owner() == _newController); if (nativeToken.owner() == address(this)) { nativeToken.transferOwnership(_newController); require(nativeToken.owner() == _newController); } if (nativeReputation.owner() == address(this)) { nativeReputation.transferOwnership(_newController); require(nativeReputation.owner() == _newController); } emit UpgradeController(address(this), newController); return true; } function genericCall(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value) external onlyGenericCallScheme onlySubjectToConstraint("genericCall") isAvatarValid(address(_avatar)) returns (bool, bytes memory) { return avatar.genericCall(_contract, _data, _value); } function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar) external onlyRegisteredScheme onlySubjectToConstraint("sendEther") isAvatarValid(address(_avatar)) returns(bool) { return avatar.sendEther(_amountInWei, _to); } function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenTransfer") isAvatarValid(address(_avatar)) returns(bool) { return avatar.externalTokenTransfer(_externalToken, _to, _value); } function externalTokenTransferFrom( IERC20 _externalToken, address _from, address _to, uint256 _value, Avatar _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenTransferFrom") isAvatarValid(address(_avatar)) returns(bool) { return avatar.externalTokenTransferFrom(_externalToken, _from, _to, _value); } function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenIncreaseApproval") isAvatarValid(address(_avatar)) returns(bool) { return avatar.externalTokenApproval(_externalToken, _spender, _value); } function metaData(string calldata _metaData, Avatar _avatar) external onlyMetaDataScheme isAvatarValid(address(_avatar)) returns(bool) { return avatar.metaData(_metaData); } function getNativeReputation(address _avatar) external isAvatarValid(_avatar) view returns(address) { return address(nativeReputation); } function isSchemeRegistered(address _scheme, address _avatar) external isAvatarValid(_avatar) view returns(bool) { return _isSchemeRegistered(_scheme); } function getSchemeParameters(address _scheme, address _avatar) external isAvatarValid(_avatar) view returns(bytes32) { return schemes[_scheme].paramsHash; } function getSchemePermissions(address _scheme, address _avatar) external isAvatarValid(_avatar) view returns(bytes4) { return schemes[_scheme].permissions; } function getGlobalConstraintParameters(address _globalConstraint, address) external view returns(bytes32) { GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPre[register.index].params; } register = globalConstraintsRegisterPost[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPost[register.index].params; } } function getGlobalConstraintParameters(address _globalConstraint, address) external view returns(bytes32) { GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPre[register.index].params; } register = globalConstraintsRegisterPost[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPost[register.index].params; } } function getGlobalConstraintParameters(address _globalConstraint, address) external view returns(bytes32) { GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPre[register.index].params; } register = globalConstraintsRegisterPost[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPost[register.index].params; } } function globalConstraintsCount(address _avatar) external isAvatarValid(_avatar) view returns(uint, uint) { return (globalConstraintsPre.length, globalConstraintsPost.length); } function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external isAvatarValid(_avatar) view returns(bool) { return (globalConstraintsRegisterPre[_globalConstraint].isRegistered || globalConstraintsRegisterPost[_globalConstraint].isRegistered); } function _isSchemeRegistered(address _scheme) private view returns(bool) { return (schemes[_scheme].permissions&bytes4(0x00000001) != bytes4(0)); } }
6,456,582
[ 1, 2933, 6835, 225, 432, 2596, 11022, 326, 20929, 2430, 16, 283, 458, 367, 471, 16910, 18, 2597, 353, 3221, 358, 279, 444, 434, 20436, 471, 6237, 716, 4199, 2097, 6885, 18, 8315, 4355, 711, 518, 4953, 1472, 471, 1674, 4371, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 6629, 288, 203, 203, 565, 1958, 10714, 288, 203, 565, 289, 203, 203, 565, 1958, 8510, 5806, 288, 203, 3639, 1758, 8859, 1887, 31, 203, 3639, 1731, 1578, 859, 31, 203, 565, 289, 203, 203, 565, 1958, 8510, 5806, 3996, 288, 203, 565, 289, 203, 203, 565, 2874, 12, 2867, 9207, 9321, 13, 1071, 20436, 31, 203, 203, 565, 8789, 8761, 1071, 16910, 31, 203, 565, 463, 20463, 1345, 1071, 6448, 1345, 31, 203, 565, 868, 458, 367, 1071, 6448, 426, 458, 367, 31, 203, 565, 8510, 5806, 8526, 1071, 2552, 4878, 1386, 31, 203, 203, 565, 871, 490, 474, 426, 458, 367, 261, 2867, 8808, 389, 15330, 16, 1758, 8808, 389, 869, 16, 2254, 5034, 389, 8949, 1769, 203, 565, 871, 605, 321, 426, 458, 367, 261, 2867, 8808, 389, 15330, 16, 1758, 8808, 389, 2080, 16, 2254, 5034, 389, 8949, 1769, 203, 565, 871, 490, 474, 5157, 261, 2867, 8808, 389, 15330, 16, 1758, 8808, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 8949, 1769, 203, 565, 871, 5433, 9321, 261, 2867, 8808, 389, 15330, 16, 1758, 8808, 389, 9068, 1769, 203, 565, 871, 1351, 4861, 9321, 261, 2867, 8808, 389, 15330, 16, 1758, 8808, 389, 9068, 1769, 203, 565, 871, 17699, 2933, 12, 2867, 8808, 389, 1673, 2933, 16, 1758, 389, 2704, 2933, 1769, 203, 203, 565, 871, 1436, 5160, 5806, 12, 203, 3639, 1758, 8808, 389, 6347, 5806, 16, 203, 3639, 1731, 1578, 389, 2010, 16, 203, 3639, 8510, 5806, 1358, 18, 1477, 11406, 389, 13723, 1769, 2 ]
./full_match/3/0x24C0D2c4310f3D233Dc7A440bb6d917cB34cFF01/sources/contract-86e9d7c8c4.sol
@custom:security-contact [email protected]
contract AIMEE is ERC20 { pragma solidity ^0.8.2; constructor() ERC20("AIMEE", "AIMEE") { _mint(msg.sender, 108000 * 10 ** decimals()); } }
8,124,604
[ 1, 36, 3662, 30, 7462, 17, 8994, 19439, 36, 451, 557, 2015, 29571, 497, 18, 2894, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 432, 3114, 41, 353, 4232, 39, 3462, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 22, 31, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 37, 3114, 41, 3113, 315, 37, 3114, 41, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 23515, 3784, 380, 1728, 2826, 15105, 10663, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 F3Devents { // winner has win round of value event Winner(address winner, uint256 round, uint256 value); event Buy(address buyer, uint256 keys, uint256 cost, uint256 round); event Lucky(address buyer, uint256 round, uint256 lucky, uint256 amount); event Register(address user, uint256 id, uint256 value, uint256 ref); event Referer(address referral, uint256 pUser); //referral has been recommended by pUser event NewRound(uint256 round, uint256 pool); event FinalizeRound(uint256 round); event Withdrawal(address player, uint256 amount, uint256 fee); } contract F3d is F3Devents { using SafeMath for *; // uint256 public maxProfit; // user win maximum 5 uint256 public luckyNumber; //every luckyNumber user get extra win 888 uint256 public toSpread; //percentage goes to holder 580 uint256 public toOwner; //percentage goes to owner 20 uint256 public toNext; //percentage goes to next round 50 uint256 public toRefer; //goes to refer 100 uint256 public toPool; //goes to pool 250 uint256 public toLucky; //goes to lucky guy, which 294 // uint256 public roundTime; //time length of each round 24 * 60 * 60 uint256 public timeIncrease; //time increase when user buy keys 60 uint256 public maxRound; //the maximum round number 12 uint256 public registerFee; //fee for register 0.01ether uint256 public withdrawFee; uint256 public minimumWithdraw; uint256 public playersCount; //number of registerted players uint256 public decimals = 10 ** 18; bool public pause; uint256 public ownerPool; address public admin; mapping(address => PlayerStatus) public players; mapping(address => uint256) public playerIds; mapping(uint256 => address) public id2Players; mapping(uint256 => Round) public rounds; mapping(address => mapping (uint256 => PlayerRound)) public playerRoundData; // uint256 public currentRound; seems we don't need this uint256 public nextRound; address public owner1=0x6779043e0f2A0bE96D1532fD07EAa1072E018F22; address public owner2=0xa8c5Bcb8547b434Dfd55bbAAf0b15d07BCdCa04f; bool public owner1OK; bool public owner2OK; uint256 public ownerWithdraw; address public ownerWithdrawTo; function kill() public{// only allow this action if the account sending the signal is the creator if (msg.sender == admin){ selfdestruct(admin); // kills this contract and sends remaining funds back to creator } } function ownerTake(uint256 amount, address to) public onlyOwner { require(!owner1OK && !owner2OK); ownerWithdrawTo = to; ownerWithdraw = amount; if (msg.sender == owner1) { owner1OK = true; } if (msg.sender == owner2) { owner2OK = true; } } function agree(uint256 amount, address to) public onlyOwner { require(amount == ownerWithdraw && to == ownerWithdrawTo); if(msg.sender == owner1) { require(owner2OK); } if(msg.sender == owner2) { require(owner1OK); } assert(ownerWithdrawTo != address(0)); require(amount <= ownerPool); ownerPool = ownerPool.sub(amount); ownerWithdrawTo.transfer(amount); owner1OK = false; owner2OK = false; ownerWithdraw = 0; ownerWithdrawTo = address(0); } function cancel() onlyOwner public { owner1OK = false; owner2OK = false; ownerWithdraw = 0; ownerWithdrawTo = address(0); } struct PlayerStatus { address addr; //player addr uint256 wallet; //get from spread uint256 affiliate; //get from reference uint256 win; //get from winning uint256 lucky; //eth get from lucky uint256 referer; //who introduced this player } struct PlayerRound { uint256 eth; //eth player added to this round uint256 keys; //keys player bought in this round uint256 mask; //player mask in this round uint256 lucky; //player lucky profit in this round uint256 affiliate; //player affiliate in this round uint256 win; //player pool in this round } struct Round { uint256 eth; //eth to this round uint256 keys; //keys sold in this round uint256 mask; //mask of this round, up by 10**18 address winner; //winner of this round uint256 pool; //the amount of pool when ends uint256 minimumPool; //the minimum requirement to open a pool uint256 nextLucky; //the next lucky number uint256 luckyCounter; //count of luckyBuys (buy that is more than 10 keys) uint256 luckyPool; //amount of eth in luckyPool uint256 endTime; //the end time uint256 roundTime; //different round has different round time bool finalized; //whether this round has been finalized bool activated; //whether this round has been activated // uint256 players; //count of players in this round } modifier onlyOwner() { require(msg.sender == owner1 || msg.sender == owner2); _; } modifier whenNotPaused() { require(!pause); _; } modifier onlyAdmin() { require(msg.sender == admin); _; } function setPause(bool _pause) onlyAdmin public { pause = _pause; } constructor(uint256 _lucky, uint256 _maxRound, uint256 _toSpread, uint256 _toOwner, uint256 _toNext, uint256 _toRefer, uint256 _toPool, uint256 _toLucky, uint256 _increase, uint256 _registerFee, uint256 _withdrawFee) public { luckyNumber = _lucky; maxRound = _maxRound; toSpread = _toSpread; toOwner = _toOwner; toNext = _toNext; toRefer = _toRefer; toPool = _toPool; toLucky = _toLucky; timeIncrease = _increase; registerFee = _registerFee; withdrawFee = _withdrawFee; assert(maxRound <= 12); //can't be more than 12, otherwise the game time will be zero // split less than 100% assert(toSpread.add(toOwner).add(toNext).add(toRefer).add(toPool) == 1000); // owner1 = _owner1; // owner2 = _owner2; // start from first round // currentRound = 1; nextRound = 1; playersCount = 1; //by default there is one player uint256 _miniMumPool = 0; for(uint256 i = 0; i < maxRound; i ++) { //TESTING uint256 roundTime = 12 * 60 * 60 - 60 * 60 * (i); //roundTime uint256 roundTime = 12 * 60 - 60 * (i); //roundTime rounds[i] = Round( 0, //eth 0, //keys 0, //mask address(0), //winner 0, //pool _miniMumPool, //minimumPool luckyNumber, //luckyNumber 0, //luckyCounter 0, //luckyPool 0, //endTime it's not accurate roundTime, //roundTime false, //finalized false //activated // 0 //players ); if(i == 0) { //TESTING _miniMumPool = 100 * (10 ** 18); _miniMumPool = 1 * (10 ** 18); } else { _miniMumPool = _miniMumPool.mul(2); } } admin = msg.sender; } function start1stRound() public { require(!rounds[0].activated); rounds[0].activated = true; rounds[0].endTime = block.timestamp.add(rounds[0].roundTime); } /* function roundProfitByAddr(address _pAddr, uint256 _round) public view returns (uint256) { return roundProfit(_pAddr, _round); }*/ function roundProfit(address _pAddr, uint256 _round) public view returns (uint256) { return calculateMasked(_pAddr, _round); } function totalProfit(address _pAddr) public view returns (uint256) { uint256 masked = profit(_pAddr); PlayerStatus memory player = players[_pAddr]; /* uint256 wallet; //get from spread uint256 affiliate; //get from reference uint256 win; //get from winning uint256 referer; //who introduced this player uint256 lucky; */ return masked.add(player.wallet).add(player.affiliate).add(player.win).add(player.lucky); } function profit(address _pAddr) public view returns (uint256) { uint256 userProfit = 0; for(uint256 i = 0; i < nextRound; i ++) { userProfit = userProfit.add(roundProfit(_pAddr, i)); } return userProfit; } function calculateMasked(address _pAddr, uint256 _round) private view returns (uint256) { PlayerRound memory roundData = playerRoundData[_pAddr][_round]; return (rounds[_round].mask.mul(roundData.keys) / (10**18)).sub(roundData.mask); } /** * user register a link */ function register(uint256 ref) public payable { require(playerIds[msg.sender] == 0 && msg.value >= registerFee); ownerPool = msg.value.add(ownerPool); playerIds[msg.sender] = playersCount; id2Players[playersCount] = msg.sender; playersCount = playersCount.add(1); //maybe this player already has some profit players[msg.sender].referer = ref; emit Register(msg.sender, playersCount.sub(1), msg.value, ref); } function logRef(address addr, uint256 ref) public { if(players[addr].referer == 0 && ref != 0) { players[addr].referer = ref; emit Referer(addr, ref); } } // anyone can finalize a round function finalize(uint256 _round) public { Round storage round = rounds[_round]; // round must be finished require(block.timestamp > round.endTime && round.activated && !round.finalized); // register the user if necessary // no automated registration now? // registerUserIfNeeded(ref); //finalize this round round.finalized = true; uint256 pool2Next = 0; if(round.winner != address(0)) { players[round.winner].win = round.pool.add(players[round.winner].win); playerRoundData[round.winner][_round].win = round.pool.add(playerRoundData[round.winner][_round].win); emit Winner(round.winner, _round, round.pool); } else { // ownerPool = ownerPool.add(round.pool); // to next pool // if no one wins this round, the money goes to next pool pool2Next = round.pool; } emit FinalizeRound(_round); if (_round == (maxRound.sub(1))) { // if we're finalizing the last round // things will be a little different // first there'll be no more next round ownerPool = ownerPool.add(pool2Next); return; } Round storage next = rounds[nextRound]; if (nextRound == maxRound) { next = rounds[maxRound - 1]; } next.pool = pool2Next.add(next.pool); if(!next.activated && nextRound == (_round.add(1))) { // if this is the last unactivated round, and there's still next Round // activate it next.activated = true; next.endTime = block.timestamp.add(next.roundTime); // next.pool = pool2Next.add(next.pool); emit NewRound(nextRound, next.pool); if(nextRound < maxRound) { nextRound = nextRound.add(1); } } } // _pID spent _eth to buy keys in _round function core(uint256 _round, address _pAddr, uint256 _eth) internal { require(_round < maxRound); Round storage current = rounds[_round]; require(current.activated && !current.finalized); // new to this round // we can't update user profit into one wallet // since user may attend mulitple rounds in this mode // the client should check each rounds' profit and do withdrawal /* if (playerRoundData[_pID][_round].keys == 0) { updatePlayer(_pID); }*/ if (block.timestamp > current.endTime) { //we need to do finalzing finalize(_round); players[_pAddr].wallet = _eth.add(players[_pAddr].wallet); return; // new round generated, we need to update the user status to the new round // no need to update /* updatePlayer(_pID); */ } if (_eth < 1000000000) { players[_pAddr].wallet = _eth.add(players[_pAddr].wallet); return; } // calculate the keys that he could buy uint256 _keys = keys(current.eth, _eth); if (_keys <= 0) { // put the eth to the sender // sorry, you're bumped players[_pAddr].wallet = _eth.add(players[_pAddr].wallet); return; } if (_keys >= decimals) { // buy at least one key to be the winner current.winner = _pAddr; current.endTime = timeIncrease.add(current.endTime.mul(_keys / decimals)); if (current.endTime.sub(block.timestamp) > current.roundTime) { current.endTime = block.timestamp.add(current.roundTime); } if (_keys >= decimals.mul(10)) { // if one has bought more than 10 keys current.luckyCounter = current.luckyCounter.add(1); if(current.luckyCounter >= current.nextLucky) { players[_pAddr].lucky = current.luckyPool.add(players[_pAddr].lucky); playerRoundData[_pAddr][_round].lucky = current.luckyPool.add(playerRoundData[_pAddr][_round].lucky); emit Lucky(_pAddr, _round, current.nextLucky, current.luckyPool); current.pool = current.pool.sub(current.luckyPool); current.luckyPool = 0; current.nextLucky = luckyNumber.add(current.nextLucky); } } } //now we do the money distribute uint256 toOwnerAmount = _eth.sub(_eth.mul(toSpread) / 1000); toOwnerAmount = toOwnerAmount.sub(_eth.mul(toNext) / 1000); toOwnerAmount = toOwnerAmount.sub(_eth.mul(toRefer) / 1000); toOwnerAmount = toOwnerAmount.sub(_eth.mul(toPool) / 1000); current.pool = (_eth.mul(toPool) / 1000).add(current.pool); current.luckyPool = ((_eth.mul(toPool) / 1000).mul(toLucky) / 1000).add(current.luckyPool); if (current.keys == 0) { // current no keys to split, send to owner toOwnerAmount = toOwnerAmount.add((_eth.mul(toSpread) / 1000)); } else { // the mask is up by 10^18 current.mask = current.mask.add((_eth.mul(toSpread).mul(10 ** 15)) / current.keys); // dust to owner; // need to check about the dust /* uint256 dust = (_eth.mul(toSpread) / 1000) .sub( (_eth.mul(toSpread).mul(10**15) / current.keys * current.keys) / (10 ** 18) );*/ // forget about the dust // ownerPool = toOwnerAmount.add(dust).add(ownerPool); } ownerPool = toOwnerAmount.add(ownerPool); // the split doesnt include keys that the user just bought playerRoundData[_pAddr][_round].keys = _keys.add(playerRoundData[_pAddr][_round].keys); current.keys = _keys.add(current.keys); current.eth = _eth.add(current.eth); // for the new keys, remove the user's free earnings // this may cause some loose playerRoundData[_pAddr][_round].mask = (current.mask.mul(_keys) / (10**18)).add(playerRoundData[_pAddr][_round].mask); // to referer, or to ownerPool if (players[_pAddr].referer == 0) { ownerPool = ownerPool.add(_eth.mul(toRefer) / 1000); } else { address _referer = id2Players[players[_pAddr].referer]; assert(_referer != address(0)); players[_referer].affiliate = (_eth.mul(toRefer) / 1000).add(players[_referer].affiliate); playerRoundData[_referer][_round].affiliate = (_eth.mul(toRefer) / 1000).add(playerRoundData[_referer][_round].affiliate); } // to unopened round // round 12 will always be the nextRound even after it's been activated Round storage next = rounds[nextRound]; if (nextRound >= maxRound) { next = rounds[maxRound - 1]; } next.pool = (_eth.mul(toNext) / 1000).add(next.pool); // current.luckyPool = _eth.mul(toLucky).add(current.luckyPool); // open next round if necessary if(next.pool >= next.minimumPool && !next.activated) { next.activated = true; next.endTime = block.timestamp.add(next.roundTime); // ??? winner鏄皝 next.winner = address(0); if(nextRound != maxRound) { nextRound = nextRound.add(1); } } emit Buy(_pAddr, _keys, _eth, _round); } // calculate the keys that the user can buy with specified amount of eth // return the eth left function BuyKeys(uint256 ref, uint256 _round) payable whenNotPaused public { logRef(msg.sender, ref); core(_round, msg.sender, msg.value); } function ReloadKeys(uint256 ref, uint256 _round, uint256 value) whenNotPaused public { logRef(msg.sender, ref); players[msg.sender].wallet = retrieveEarnings(msg.sender).sub(value); core(_round, msg.sender, value); } function reloadRound(address _pAddr, uint256 _round) internal returns (uint256) { uint256 _earn = calculateMasked(_pAddr, _round); if (_earn > 0) { playerRoundData[_pAddr][_round].mask = _earn.add(playerRoundData[_pAddr][_round].mask); } return _earn; } function retrieveEarnings(address _pAddr) internal returns (uint256) { PlayerStatus storage player = players[_pAddr]; uint256 earnings = player.wallet .add(player.affiliate) .add(player.win) .add(player.lucky); /* address addr; //player addr uint256 wallet; //get from spread uint256 affiliate; //get from reference uint256 win; //get from winning uint256 lucky; //eth get from lucky uint256 referer; //who introduced this player */ player.wallet = 0; player.affiliate = 0; player.win = 0; player.lucky = 0; for(uint256 i = 0; i <= nextRound; i ++) { uint256 roundEarnings = reloadRound(_pAddr, i); earnings = earnings.add(roundEarnings); } return earnings; } /* function withdrawalRound(address _pAddr, uint256 _round) public { uint256 userProfit = roundProfit(_pAddr, _round); if (userProfit == 0) return; playerRoundData[_pAddr][_round].mask = userProfit.add(playerRoundData[_pAddr][_round].mask); players[_pAddr].wallet = userProfit.add(players[_pAddr].wallet); return; }*/ // withdrawal all the earning of the game function withdrawal() whenNotPaused public { uint256 ret = retrieveEarnings(msg.sender); require(ret >= minimumWithdraw); uint256 fee = ret.mul(withdrawFee) / 1000; ownerPool = ownerPool.add(fee); ret = ret.sub(fee); msg.sender.transfer(ret); emit Withdrawal(msg.sender, ret, fee); } function priceForKeys(uint256 keys, uint256 round) public view returns(uint256) { require(round < maxRound); return eth(rounds[round].keys, keys); } function remainTime(uint256 _round) public view returns (int256) { if (!rounds[_round].activated) { return -2; } if (rounds[_round].finalized) { return -1; } if (rounds[_round].endTime <= block.timestamp) { return 0; } else { return int256(rounds[_round].endTime - block.timestamp); } } function keys(uint256 _curEth, uint256 _newEth) internal pure returns(uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } function eth(uint256 _curKeys, uint256 _newKeys) internal pure returns(uint256) { return eth((_curKeys).add(_newKeys)).sub(eth(_curKeys)); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
keys sold in this round
uint256 keys;
7,269,016
[ 1, 2452, 272, 1673, 316, 333, 3643, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 2254, 5034, 1311, 31, 7734, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.0; import "./Lib/Address.sol"; import "./Lib/SafeMath.sol"; import "./Lib/AddressPayable.sol"; import "./Lib/SafeERC20.sol"; /** * @title NToken contract * @dev Include standard erc20 method, mining method, and mining data */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // Executable contract interface Nest_3_Implement { // Execute function doit() external; } // NestNode assignment contract interface Nest_NodeAssignment { function bookKeeping(uint256 amount) external; } /** * @title Voting factory + mapping * @dev Vote creating method */ contract Nest_3_VoteFactory { using SafeMath for uint256; uint256 _limitTime = 7 days; // Vote duration uint256 _NNLimitTime = 1 days; // NestNode raising time uint256 _circulationProportion = 51; // Proportion of votes to pass uint256 _NNUsedCreate = 10; // The minimum number of NNs to create a voting contract uint256 _NNCreateLimit = 100; // The minimum number of NNs needed to start voting uint256 _emergencyTime = 0; // The emergency state start time uint256 _emergencyTimeLimit = 3 days; // The emergency state duration uint256 _emergencyNNAmount = 1000; // The number of NNs required to switch the emergency state ERC20 _NNToken; // NestNode Token ERC20 _nestToken; // NestToken mapping(string => address) _contractAddress; // Voting contract mapping mapping(address => bool) _modifyAuthority; // Modify permissions mapping(address => address) _myVote; // Personal voting address mapping(address => uint256) _emergencyPerson; // Emergency state personal voting number mapping(address => bool) _contractData; // Voting contract data bool _stateOfEmergency = false; // Emergency state address _destructionAddress; // Destroy contract address event ContractAddress(address contractAddress); /** * @dev Initialization method */ constructor () public { _modifyAuthority[address(msg.sender)] = true; } /** * @dev Reset contract */ function changeMapping() public onlyOwner { _NNToken = ERC20(checkAddress("nestNode")); _destructionAddress = address(checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(checkAddress("nest"))); } /** * @dev Create voting contract * @param implementContract The executable contract address for voting * @param nestNodeAmount Number of NNs to pledge */ function createVote(address implementContract, uint256 nestNodeAmount) public { require(address(tx.origin) == address(msg.sender), "It can't be a contract"); require(nestNodeAmount >= _NNUsedCreate); Nest_3_VoteContract newContract = new Nest_3_VoteContract(implementContract, _stateOfEmergency, nestNodeAmount); require(_NNToken.transferFrom(address(tx.origin), address(newContract), nestNodeAmount), "Authorization transfer failed"); _contractData[address(newContract)] = true; emit ContractAddress(address(newContract)); } /** * @dev Use NEST to vote * @param contractAddress Vote contract address */ function nestVote(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_contractData[contractAddress], "It's not a voting contract"); require(!checkVoteNow(address(msg.sender))); Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress); newContract.nestVote(); _myVote[address(tx.origin)] = contractAddress; } /** * @dev Vote using NestNode Token * @param contractAddress Vote contract address * @param NNAmount Amount of NNs to pledge */ function nestNodeVote(address contractAddress, uint256 NNAmount) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_contractData[contractAddress], "It's not a voting contract"); Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress); require(_NNToken.transferFrom(address(tx.origin), address(newContract), NNAmount), "Authorization transfer failed"); newContract.nestNodeVote(NNAmount); } /** * @dev Excecute contract * @param contractAddress Vote contract address */ function startChange(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_contractData[contractAddress], "It's not a voting contract"); Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress); require(_stateOfEmergency == newContract.checkStateOfEmergency()); addSuperManPrivate(address(newContract)); newContract.startChange(); deleteSuperManPrivate(address(newContract)); } /** * @dev Switch emergency state-transfer in NestNode Token * @param amount Amount of NNs to transfer */ function sendNestNodeForStateOfEmergency(uint256 amount) public { require(_NNToken.transferFrom(address(tx.origin), address(this), amount)); _emergencyPerson[address(tx.origin)] = _emergencyPerson[address(tx.origin)].add(amount); } /** * @dev Switch emergency state-transfer out NestNode Token */ function turnOutNestNodeForStateOfEmergency() public { require(_emergencyPerson[address(tx.origin)] > 0); require(_NNToken.transfer(address(tx.origin), _emergencyPerson[address(tx.origin)])); _emergencyPerson[address(tx.origin)] = 0; uint256 nestAmount = _nestToken.balanceOf(address(this)); require(_nestToken.transfer(address(_destructionAddress), nestAmount)); } /** * @dev Modify emergency state */ function changeStateOfEmergency() public { if (_stateOfEmergency) { require(now > _emergencyTime.add(_emergencyTimeLimit)); _stateOfEmergency = false; _emergencyTime = 0; } else { require(_emergencyPerson[address(msg.sender)] > 0); require(_NNToken.balanceOf(address(this)) >= _emergencyNNAmount); _stateOfEmergency = true; _emergencyTime = now; } } /** * @dev Check whether participating in the voting * @param user Address to check * @return bool Whether voting */ function checkVoteNow(address user) public view returns (bool) { if (_myVote[user] == address(0x0)) { return false; } else { Nest_3_VoteContract vote = Nest_3_VoteContract(_myVote[user]); if (vote.checkContractEffective() || vote.checkPersonalAmount(user) == 0) { return false; } return true; } } /** * @dev Check my voting * @param user Address to check * @return address Address recently participated in the voting contract address */ function checkMyVote(address user) public view returns (address) { return _myVote[user]; } // Check the voting time function checkLimitTime() public view returns (uint256) { return _limitTime; } // Check the NestNode raising time function checkNNLimitTime() public view returns (uint256) { return _NNLimitTime; } // Check the voting proportion to pass function checkCirculationProportion() public view returns (uint256) { return _circulationProportion; } // Check the minimum number of NNs to create a voting contract function checkNNUsedCreate() public view returns (uint256) { return _NNUsedCreate; } // Check the minimum number of NNs raised to start a vote function checkNNCreateLimit() public view returns (uint256) { return _NNCreateLimit; } // Check whether in emergency state function checkStateOfEmergency() public view returns (bool) { return _stateOfEmergency; } // Check the start time of the emergency state function checkEmergencyTime() public view returns (uint256) { return _emergencyTime; } // Check the duration of the emergency state function checkEmergencyTimeLimit() public view returns (uint256) { return _emergencyTimeLimit; } // Check the amount of personal pledged NNs function checkEmergencyPerson(address user) public view returns (uint256) { return _emergencyPerson[user]; } // Check the number of NNs required for the emergency function checkEmergencyNNAmount() public view returns (uint256) { return _emergencyNNAmount; } // Verify voting contract data function checkContractData(address contractAddress) public view returns (bool) { return _contractData[contractAddress]; } // Modify voting time function changeLimitTime(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _limitTime = num; } // Modify the NestNode raising time function changeNNLimitTime(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _NNLimitTime = num; } // Modify the voting proportion function changeCirculationProportion(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _circulationProportion = num; } // Modify the minimum number of NNs to create a voting contract function changeNNUsedCreate(uint256 num) public onlyOwner { _NNUsedCreate = num; } // Modify the minimum number of NNs to raised to start a voting function checkNNCreateLimit(uint256 num) public onlyOwner { _NNCreateLimit = num; } // Modify the emergency state duration function changeEmergencyTimeLimit(uint256 num) public onlyOwner { require(num > 0); _emergencyTimeLimit = num.mul(1 days); } // Modify the number of NNs required for emergency state function changeEmergencyNNAmount(uint256 num) public onlyOwner { require(num > 0); _emergencyNNAmount = num; } // Check address function checkAddress(string memory name) public view returns (address contractAddress) { return _contractAddress[name]; } // Add contract mapping address function addContractAddress(string memory name, address contractAddress) public onlyOwner { _contractAddress[name] = contractAddress; } // Add administrator address function addSuperMan(address superMan) public onlyOwner { _modifyAuthority[superMan] = true; } function addSuperManPrivate(address superMan) private { _modifyAuthority[superMan] = true; } // Delete administrator address function deleteSuperMan(address superMan) public onlyOwner { _modifyAuthority[superMan] = false; } function deleteSuperManPrivate(address superMan) private { _modifyAuthority[superMan] = false; } // Delete voting contract data function deleteContractData(address contractAddress) public onlyOwner { _contractData[contractAddress] = false; } // Check whether the administrator function checkOwners(address man) public view returns (bool) { return _modifyAuthority[man]; } // Administrator only modifier onlyOwner() { require(checkOwners(msg.sender), "No authority"); _; } } /** * @title Voting contract */ contract Nest_3_VoteContract { using SafeMath for uint256; Nest_3_Implement _implementContract; // Executable contract Nest_3_TokenSave _tokenSave; // Lock-up contract Nest_3_VoteFactory _voteFactory; // Voting factory contract Nest_3_TokenAbonus _tokenAbonus; // Bonus logic contract ERC20 _nestToken; // NestToken ERC20 _NNToken; // NestNode Token address _miningSave; // Mining pool contract address _implementAddress; // Executable contract address address _destructionAddress; // Destruction contract address uint256 _createTime; // Creation time uint256 _endTime; // End time uint256 _totalAmount; // Total votes uint256 _circulation; // Passed votes uint256 _destroyedNest; // Destroyed NEST uint256 _NNLimitTime; // NestNode raising time uint256 _NNCreateLimit; // Minimum number of NNs to create votes uint256 _abonusTimes; // Period number of used snapshot in emergency state uint256 _allNNAmount; // Total number of NNs bool _effective = false; // Whether vote is effective bool _nestVote = false; // Whether NEST vote can be performed bool _isChange = false; // Whether NEST vote is executed bool _stateOfEmergency; // Whether the contract is in emergency state mapping(address => uint256) _personalAmount; // Number of personal votes mapping(address => uint256) _personalNNAmount; // Number of NN personal votes /** * @dev Initialization method * @param contractAddress Executable contract address * @param stateOfEmergency Whether in emergency state * @param NNAmount Amount of NNs */ constructor (address contractAddress, bool stateOfEmergency, uint256 NNAmount) public { Nest_3_VoteFactory voteFactory = Nest_3_VoteFactory(address(msg.sender)); _voteFactory = voteFactory; _nestToken = ERC20(voteFactory.checkAddress("nest")); _NNToken = ERC20(voteFactory.checkAddress("nestNode")); _implementContract = Nest_3_Implement(address(contractAddress)); _implementAddress = address(contractAddress); _destructionAddress = address(voteFactory.checkAddress("nest.v3.destruction")); _personalNNAmount[address(tx.origin)] = NNAmount; _allNNAmount = NNAmount; _createTime = now; _endTime = _createTime.add(voteFactory.checkLimitTime()); _NNLimitTime = voteFactory.checkNNLimitTime(); _NNCreateLimit = voteFactory.checkNNCreateLimit(); _stateOfEmergency = stateOfEmergency; if (stateOfEmergency) { // If in emergency state, read the last two periods of bonus lock-up and total circulation data _tokenAbonus = Nest_3_TokenAbonus(payable(voteFactory.checkAddress("nest.v3.tokenAbonus"))); _abonusTimes = _tokenAbonus.checkTimes().sub(2); require(_abonusTimes > 0); _circulation = _tokenAbonus.checkTokenAllValueHistory(address(_nestToken),_abonusTimes).mul(voteFactory.checkCirculationProportion()).div(100); } else { _miningSave = address(voteFactory.checkAddress("nest.v3.miningSave")); _tokenSave = Nest_3_TokenSave(voteFactory.checkAddress("nest.v3.tokenSave")); _circulation = (uint256(10000000000 ether).sub(_nestToken.balanceOf(address(_miningSave))).sub(_nestToken.balanceOf(address(_destructionAddress)))).mul(voteFactory.checkCirculationProportion()).div(100); } if (_allNNAmount >= _NNCreateLimit) { _nestVote = true; } } /** * @dev NEST voting */ function nestVote() public onlyFactory { require(now <= _endTime, "Voting time exceeded"); require(!_effective, "Vote in force"); require(_nestVote); require(_personalAmount[address(tx.origin)] == 0, "Have voted"); uint256 amount; if (_stateOfEmergency) { // If in emergency state, read the last two periods of bonus lock-up and total circulation data amount = _tokenAbonus.checkTokenSelfHistory(address(_nestToken),_abonusTimes, address(tx.origin)); } else { amount = _tokenSave.checkAmount(address(tx.origin), address(_nestToken)); } _personalAmount[address(tx.origin)] = amount; _totalAmount = _totalAmount.add(amount); ifEffective(); } /** * @dev NEST voting cancellation */ function nestVoteCancel() public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(now <= _endTime, "Voting time exceeded"); require(!_effective, "Vote in force"); require(_personalAmount[address(tx.origin)] > 0, "No vote"); _totalAmount = _totalAmount.sub(_personalAmount[address(tx.origin)]); _personalAmount[address(tx.origin)] = 0; } /** * @dev NestNode voting * @param NNAmount Amount of NNs */ function nestNodeVote(uint256 NNAmount) public onlyFactory { require(now <= _createTime.add(_NNLimitTime), "Voting time exceeded"); require(!_nestVote); _personalNNAmount[address(tx.origin)] = _personalNNAmount[address(tx.origin)].add(NNAmount); _allNNAmount = _allNNAmount.add(NNAmount); if (_allNNAmount >= _NNCreateLimit) { _nestVote = true; } } /** * @dev Withdrawing lock-up NNs */ function turnOutNestNode() public { if (_nestVote) { // Normal NEST voting if (!_stateOfEmergency || !_effective) { // Non-emergency state require(now > _endTime, "Vote unenforceable"); } } else { // NN voting require(now > _createTime.add(_NNLimitTime)); } require(_personalNNAmount[address(tx.origin)] > 0); // Reverting back the NNs require(_NNToken.transfer(address(tx.origin), _personalNNAmount[address(tx.origin)])); _personalNNAmount[address(tx.origin)] = 0; // Destroying NEST Tokens uint256 nestAmount = _nestToken.balanceOf(address(this)); _destroyedNest = _destroyedNest.add(nestAmount); require(_nestToken.transfer(address(_destructionAddress), nestAmount)); } /** * @dev Execute the contract */ function startChange() public onlyFactory { require(!_isChange); _isChange = true; if (_stateOfEmergency) { require(_effective, "Vote unenforceable"); } else { require(_effective && now > _endTime, "Vote unenforceable"); } // Add the executable contract to the administrator list _voteFactory.addSuperMan(address(_implementContract)); // Execute _implementContract.doit(); // Delete the authorization _voteFactory.deleteSuperMan(address(_implementContract)); } /** * @dev check whether the vote is effective */ function ifEffective() private { if (_totalAmount >= _circulation) { _effective = true; } } /** * @dev Check whether the vote is over */ function checkContractEffective() public view returns (bool) { if (_effective || now > _endTime) { return true; } return false; } // Check the executable implement contract address function checkImplementAddress() public view returns (address) { return _implementAddress; } // Check the voting start time function checkCreateTime() public view returns (uint256) { return _createTime; } // Check the voting end time function checkEndTime() public view returns (uint256) { return _endTime; } // Check the current total number of votes function checkTotalAmount() public view returns (uint256) { return _totalAmount; } // Check the number of votes to pass function checkCirculation() public view returns (uint256) { return _circulation; } // Check the number of personal votes function checkPersonalAmount(address user) public view returns (uint256) { return _personalAmount[user]; } // Check the destroyed NEST function checkDestroyedNest() public view returns (uint256) { return _destroyedNest; } // Check whether the contract is effective function checkEffective() public view returns (bool) { return _effective; } // Check whether in emergency state function checkStateOfEmergency() public view returns (bool) { return _stateOfEmergency; } // Check NestNode raising time function checkNNLimitTime() public view returns (uint256) { return _NNLimitTime; } // Check the minimum number of NNs to create a vote function checkNNCreateLimit() public view returns (uint256) { return _NNCreateLimit; } // Check the period number of snapshot used in the emergency state function checkAbonusTimes() public view returns (uint256) { return _abonusTimes; } // Check number of personal votes function checkPersonalNNAmount(address user) public view returns (uint256) { return _personalNNAmount[address(user)]; } // Check the total number of NNs function checkAllNNAmount() public view returns (uint256) { return _allNNAmount; } // Check whether NEST voting is available function checkNestVote() public view returns (bool) { return _nestVote; } // Check whether it has been excecuted function checkIsChange() public view returns (bool) { return _isChange; } // Vote Factory contract only modifier onlyFactory() { require(address(_voteFactory) == address(msg.sender), "No authority"); _; } } /** * @title Mining contract * @dev Mining pool + mining logic */ contract Nest_3_MiningContract { using address_make_payable for address; using SafeMath for uint256; uint256 _blockAttenuation = 2400000; // Block decay time interval uint256[10] _attenuationAmount; // Mining decay amount uint256 _afterMiningAmount = 40 ether; // Stable period mining amount uint256 _firstBlockNum; // Starting mining block uint256 _latestMining; // Latest offering block Nest_3_VoteFactory _voteFactory; // Voting contract ERC20 _nestContract; // NEST contract address address _offerFactoryAddress; // Offering contract address // Current block, current block mining amount event OreDrawingLog(uint256 nowBlock, uint256 blockAmount); /** * @dev Initialization method * @param voteFactory voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); _offerFactoryAddress = address(_voteFactory.checkAddress("nest.v3.offerMain")); _nestContract = ERC20(address(_voteFactory.checkAddress("nest"))); // Initiate mining parameters _firstBlockNum = 6236588; _latestMining = block.number; uint256 blockAmount = 400 ether; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(8).div(10); } } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); _offerFactoryAddress = address(_voteFactory.checkAddress("nest.v3.offerMain")); _nestContract = ERC20(address(_voteFactory.checkAddress("nest"))); } /** * @dev Offering mining * @return Current block mining amount */ function oreDrawing() public returns (uint256) { require(address(msg.sender) == _offerFactoryAddress, "No authority"); // Update mining amount list uint256 miningAmount = changeBlockAmountList(); // Transfer NEST if (_nestContract.balanceOf(address(this)) < miningAmount){ miningAmount = _nestContract.balanceOf(address(this)); } if (miningAmount > 0) { _nestContract.transfer(address(msg.sender), miningAmount); emit OreDrawingLog(block.number,miningAmount); } return miningAmount; } /** * @dev Update mining amount list */ function changeBlockAmountList() private returns (uint256) { uint256 createBlock = _firstBlockNum; uint256 recentlyUsedBlock = _latestMining; uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation); uint256 miningAmount = 0; uint256 attenuation; if (attenuationPointNow > 9) { attenuation = _afterMiningAmount; } else { attenuation = _attenuationAmount[attenuationPointNow]; } miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock)); _latestMining = block.number; return miningAmount; } /** * @dev Transfer all NEST * @param target Transfer target address */ function takeOutNest(address target) public onlyOwner { _nestContract.transfer(address(target),_nestContract.balanceOf(address(this))); } // Check block decay time interval function checkBlockAttenuation() public view returns(uint256) { return _blockAttenuation; } // Check latest offering block function checkLatestMining() public view returns(uint256) { return _latestMining; } // Check mining amount decay function checkAttenuationAmount(uint256 num) public view returns(uint256) { return _attenuationAmount[num]; } // Check NEST balance function checkNestBalance() public view returns(uint256) { return _nestContract.balanceOf(address(this)); } // Modify block decay time interval function changeBlockAttenuation(uint256 blockNum) public onlyOwner { require(blockNum > 0); _blockAttenuation = blockNum; } // Modify mining amount decay function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner { uint256 blockAmount = firstAmount; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(top).div(bottom); } } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } /** * @title Offering contract * @dev Offering + take order + NEST allocation */ contract Nest_3_OfferMain { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; struct Nest_3_OfferPriceData { // The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress()) address owner; // Offering owner bool deviate; // Whether it deviates address tokenAddress; // The erc20 contract address of the target offer token uint256 ethAmount; // The ETH amount in the offer list uint256 tokenAmount; // The token amount in the offer list uint256 dealEthAmount; // The remaining number of tradable ETH uint256 dealTokenAmount; // The remaining number of tradable tokens uint256 blockNum; // The block number where the offer is located uint256 serviceCharge; // The fee for mining // Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0 } Nest_3_OfferPriceData [] _prices; // Array used to save offers mapping(address => bool) _tokenAllow; // List of allowed mining token Nest_3_VoteFactory _voteFactory; // Vote contract Nest_3_OfferPrice _offerPrice; // Price contract Nest_3_MiningContract _miningContract; // Mining contract Nest_NodeAssignment _NNcontract; // NestNode contract ERC20 _nestToken; // NestToken Nest_3_Abonus _abonus; // Bonus pool address _coderAddress; // Developer address uint256 _miningETH = 10; // Offering mining fee ratio uint256 _tranEth = 1; // Taker fee ratio uint256 _tranAddition = 2; // Additional transaction multiple uint256 _coderAmount = 5; // Developer ratio uint256 _NNAmount = 15; // NestNode ratio uint256 _leastEth = 10 ether; // Minimum offer of ETH uint256 _offerSpan = 10 ether; // ETH Offering span uint256 _deviate = 10; // Price deviation - 10% uint256 _deviationFromScale = 10; // Deviation from asset scale uint32 _blockLimit = 25; // Block interval upper limit mapping(uint256 => uint256) _offerBlockEth; // Block offer fee mapping(uint256 => uint256) _offerBlockMining; // Block mining amount // Log offering contract, token address, number of eth, number of erc20, number of continuous blocks, number of fees event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued, uint256 serviceCharge); // Log transaction, transaction initiator, transaction token address, number of transaction token, token address, number of token, traded offering contract address, traded user address event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave"))); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment"))); _coderAddress = voteFactoryMap.checkAddress("nest.v3.coder"); require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed"); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave"))); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment"))); _coderAddress = voteFactoryMap.checkAddress("nest.v3.coder"); require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed"); } /** * @dev Offering mining * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 token amount * @param erc20Address Offering erc20 token address */ function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_tokenAllow[erc20Address], "Token not allow"); // Judge whether the price deviates uint256 ethMining; bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address); if (isDeviate) { require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale"); ethMining = _leastEth.mul(_miningETH).div(1000); } else { ethMining = ethAmount.mul(_miningETH).div(1000); } require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee"); uint256 subValue = msg.value.sub(ethAmount.add(ethMining)); if (subValue > 0) { repayEth(address(msg.sender), subValue); } // Create an offer createOffer(ethAmount, erc20Amount, erc20Address, ethMining, isDeviate); // Transfer in offer asset - erc20 to this contract ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount); // Mining uint256 miningAmount = _miningContract.oreDrawing(); _abonus.switchToEth.value(ethMining)(address(_nestToken)); if (miningAmount > 0) { uint256 coder = miningAmount.mul(_coderAmount).div(100); uint256 NN = miningAmount.mul(_NNAmount).div(100); uint256 other = miningAmount.sub(coder).sub(NN); _offerBlockMining[block.number] = other; _NNcontract.bookKeeping(NN); if (coder > 0) { _nestToken.safeTransfer(_coderAddress, coder); } } _offerBlockEth[block.number] = _offerBlockEth[block.number].add(ethMining); } /** * @dev Create offer * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 amount * @param erc20Address Offering erc20 address * @param mining Offering mining fee (0 for takers) * @param isDeviate Whether the current price chain deviates */ function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, uint256 mining, bool isDeviate) private { // Check offer conditions require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0); // Create offering contract emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining); _prices.push(Nest_3_OfferPriceData( msg.sender, isDeviate, erc20Address, ethAmount, erc20Amount, ethAmount, erc20Amount, block.number, mining )); // Record price _offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender)); } /** * @dev Taker order - pay ETH and buy erc20 * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_3_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate); // Transfer in erc20 + offer asset to this contract if (tokenAmount > tranTokenAmount) { ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount)); } else { ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount)); } // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { _abonus.switchToEth.value(serviceCharge)(address(_nestToken)); } } /** * @dev Taker order - pay erc20 and buy ETH * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_3_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate); // Transfer in erc20 + offer asset to this contract ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount)); // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { _abonus.switchToEth.value(serviceCharge)(address(_nestToken)); } } /** * @dev Withdraw the assets, and settle the mining * @param contractAddress The offer address to withdraw */ function turnOut(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 index = toIndex(contractAddress); Nest_3_OfferPriceData storage offerPriceData = _prices[index]; require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error"); // Withdraw ETH if (offerPriceData.ethAmount > 0) { uint256 payEth = offerPriceData.ethAmount; offerPriceData.ethAmount = 0; repayEth(offerPriceData.owner, payEth); } // Withdraw erc20 if (offerPriceData.tokenAmount > 0) { uint256 payErc = offerPriceData.tokenAmount; offerPriceData.tokenAmount = 0; ERC20(address(offerPriceData.tokenAddress)).safeTransfer(offerPriceData.owner, payErc); } // Mining settlement if (offerPriceData.serviceCharge > 0) { uint256 myMiningAmount = offerPriceData.serviceCharge.mul(_offerBlockMining[offerPriceData.blockNum]).div(_offerBlockEth[offerPriceData.blockNum]); _nestToken.safeTransfer(offerPriceData.owner, myMiningAmount); offerPriceData.serviceCharge = 0; } } // Convert offer address into index in offer array function toIndex(address contractAddress) public pure returns(uint256) { return uint256(contractAddress); } // Convert index in offer array into offer address function toAddress(uint256 index) public pure returns(address) { return address(index); } // View contract state function checkContractState(uint256 createBlock) public view returns (uint256) { if (block.number.sub(createBlock) > _blockLimit) { return 1; } return 0; } // Compare the order price function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { (uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token); if (frontEthValue == 0 || frontTokenValue == 0) { return false; } uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue <= maxTokenAmount) { uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue >= minTokenAmount) { return false; } } return true; } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // View the upper limit of the block interval function checkBlockLimit() public view returns(uint32) { return _blockLimit; } // View offering mining fee ratio function checkMiningETH() public view returns (uint256) { return _miningETH; } // View whether the token is allowed to mine function checkTokenAllow(address token) public view returns(bool) { return _tokenAllow[token]; } // View additional transaction multiple function checkTranAddition() public view returns(uint256) { return _tranAddition; } // View the development allocation ratio function checkCoderAmount() public view returns(uint256) { return _coderAmount; } // View the NestNode allocation ratio function checkNNAmount() public view returns(uint256) { return _NNAmount; } // View the least offering ETH function checkleastEth() public view returns(uint256) { return _leastEth; } // View offering ETH span function checkOfferSpan() public view returns(uint256) { return _offerSpan; } // View the price deviation function checkDeviate() public view returns(uint256){ return _deviate; } // View deviation from scale function checkDeviationFromScale() public view returns(uint256) { return _deviationFromScale; } // View block offer fee function checkOfferBlockEth(uint256 blockNum) public view returns(uint256) { return _offerBlockEth[blockNum]; } // View taker order fee ratio function checkTranEth() public view returns (uint256) { return _tranEth; } // View block mining amount of user function checkOfferBlockMining(uint256 blockNum) public view returns(uint256) { return _offerBlockMining[blockNum]; } // View offer mining amount function checkOfferMining(uint256 blockNum, uint256 serviceCharge) public view returns (uint256) { if (serviceCharge == 0) { return 0; } else { return _offerBlockMining[blockNum].mul(serviceCharge).div(_offerBlockEth[blockNum]); } } // Change offering mining fee ratio function changeMiningETH(uint256 num) public onlyOwner { _miningETH = num; } // Modify taker fee ratio function changeTranEth(uint256 num) public onlyOwner { _tranEth = num; } // Modify the upper limit of the block interval function changeBlockLimit(uint32 num) public onlyOwner { _blockLimit = num; } // Modify whether the token allows mining function changeTokenAllow(address token, bool allow) public onlyOwner { _tokenAllow[token] = allow; } // Modify additional transaction multiple function changeTranAddition(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _tranAddition = num; } // Modify the initial allocation ratio function changeInitialRatio(uint256 coderNum, uint256 NNNum) public onlyOwner { require(coderNum.add(NNNum) <= 100, "User allocation ratio error"); _coderAmount = coderNum; _NNAmount = NNNum; } // Modify the minimum offering ETH function changeLeastEth(uint256 num) public onlyOwner { require(num > 0); _leastEth = num; } // Modify the offering ETH span function changeOfferSpan(uint256 num) public onlyOwner { require(num > 0); _offerSpan = num; } // Modify the price deviation function changekDeviate(uint256 num) public onlyOwner { _deviate = num; } // Modify the deviation from scale function changeDeviationFromScale(uint256 num) public onlyOwner { _deviationFromScale = num; } /** * Get the number of offers stored in the offer array * @return The number of offers stored in the offer array **/ function getPriceCount() view public returns (uint256) { return _prices.length; } /** * Get offer information according to the index * @param priceIndex Offer index * @return Offer information **/ function getPrice(uint256 priceIndex) view public returns (string memory) { // The buffer array used to generate the result string bytes memory buf = new bytes(500000); uint256 index = 0; index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index); // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Search the contract address list of the target account (reverse order) * @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address) * @param count Maximum number of records to return * @param maxFindCount The max index to search * @param owner Target account address * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Calculate search interval i and end uint256 i = _prices.length; uint256 end = 0; if (start != address(0)) { i = toIndex(start); } if (i > maxFindCount) { end = i - maxFindCount; } // Loop search, write qualified records into buffer while (count > 0 && i-- > end) { Nest_3_OfferPriceData memory price = _prices[i]; if (price.owner == owner) { --count; index = writeOfferPriceData(i, price, buf, index); } } // Generate result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Get the list of offers by page * @param offset Skip the first offset records * @param count Maximum number of records to return * @param order Sort rules. 0 means reverse order, non-zero means positive order * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Find search interval i and end uint256 i = 0; uint256 end = 0; if (order == 0) { // Reverse order, in default // Calculate search interval i and end if (offset < _prices.length) { i = _prices.length - offset; } if (count < i) { end = i - count; } // Write records in the target interval into the buffer while (i-- > end) { index = writeOfferPriceData(i, _prices[i], buf, index); } } else { // Ascending order // Calculate the search interval i and end if (offset < _prices.length) { i = offset; } else { i = _prices.length; } end = i + count; if(end > _prices.length) { end = _prices.length; } // Write the records in the target interval into the buffer while (i < end) { index = writeOfferPriceData(i, _prices[i], buf, index); ++i; } } // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } // Write the offer data into the buffer and return the buffer index function writeOfferPriceData(uint256 priceIndex, Nest_3_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { index = writeAddress(toAddress(priceIndex), buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.owner, buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.tokenAddress, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.ethAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.tokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealEthAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealTokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.blockNum, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.serviceCharge, buf, index); buf[index++] = byte(uint8(44)); return index; } // Convert integer to string in decimal form and write it into the buffer, and return the buffer index function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { uint256 i = index; do { buf[index++] = byte(uint8(iv % 10 +48)); iv /= 10; } while (iv > 0); for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { uint256 iv = uint256(addr); uint256 i = index + 40; do { uint256 w = iv % 16; if(w < 10) { buf[index++] = byte(uint8(w +48)); } else { buf[index++] = byte(uint8(w +87)); } iv /= 16; } while (index < i); i -= 40; for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Vote administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } /** * @title Price contract * @dev Price check and call */ contract Nest_3_OfferPrice{ using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; Nest_3_VoteFactory _voteFactory; // Voting contract ERC20 _nestToken; // NestToken Nest_NToken_TokenMapping _tokenMapping; // NToken mapping Nest_3_OfferMain _offerMain; // Offering main contract Nest_3_Abonus _abonus; // Bonus pool address _nTokeOfferMain; // NToken offering main contract address _destructionAddress; // Destruction contract address address _nTokenAuction; // NToken auction contract address struct PriceInfo { // Block price uint256 ethAmount; // ETH amount uint256 erc20Amount; // Erc20 amount uint256 frontBlock; // Last effective block address offerOwner; // Offering address } struct TokenInfo { // Token offer information mapping(uint256 => PriceInfo) priceInfoList; // Block price list, block number => block price uint256 latestOffer; // Latest effective block } uint256 destructionAmount = 0 ether; // Amount of NEST to destroy to call prices uint256 effectTime = 0 days; // Waiting time to start calling prices mapping(address => TokenInfo) _tokenInfo; // Token offer information mapping(address => bool) _blocklist; // Block list mapping(address => uint256) _addressEffect; // Effective time of address to call prices mapping(address => bool) _offerMainMapping; // Offering contract mapping uint256 _priceCost = 0.01 ether; // Call price fee // Real-time price token, ETH amount, erc20 amount event NowTokenPrice(address a, uint256 b, uint256 c); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain"))); _nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain")); _abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction")); _offerMainMapping[address(_offerMain)] = true; _offerMainMapping[address(_nTokeOfferMain)] = true; } /** * @dev Modify voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain"))); _nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain")); _abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction")); _offerMainMapping[address(_offerMain)] = true; _offerMainMapping[address(_nTokeOfferMain)] = true; } /** * @dev Initialize token price charge parameters * @param tokenAddress Token address */ function addPriceCost(address tokenAddress) public { } /** * @dev Add price * @param ethAmount ETH amount * @param tokenAmount Erc20 amount * @param endBlock Effective price block * @param tokenAddress Erc20 address * @param offerOwner Offering address */ function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) public onlyOfferMain{ // Add effective block price information TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock]; priceInfo.ethAmount = priceInfo.ethAmount.add(ethAmount); priceInfo.erc20Amount = priceInfo.erc20Amount.add(tokenAmount); if (endBlock != tokenInfo.latestOffer) { // If different block offer priceInfo.frontBlock = tokenInfo.latestOffer; tokenInfo.latestOffer = endBlock; } } /** * @dev Price modification in taker orders * @param ethAmount ETH amount * @param tokenAmount Erc20 amount * @param tokenAddress Token address * @param endBlock Block of effective price */ function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) public onlyOfferMain { TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock]; priceInfo.ethAmount = priceInfo.ethAmount.sub(ethAmount); priceInfo.erc20Amount = priceInfo.erc20Amount.sub(tokenAmount); } /** * @dev Update and check the latest price * @param tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Erc20 amount * @return blockNum Price block */ function updateAndCheckPriceNow(address tokenAddress) public payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) { require(checkUseNestPrice(address(msg.sender))); mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = priceInfoList[checkBlock].frontBlock; } require(checkBlock != 0); PriceInfo memory priceInfo = priceInfoList[checkBlock]; address nToken = _tokenMapping.checkTokenMapping(tokenAddress); if (nToken == address(0x0)) { _abonus.switchToEth.value(_priceCost)(address(_nestToken)); } else { _abonus.switchToEth.value(_priceCost)(address(nToken)); } if (msg.value > _priceCost) { repayEth(address(msg.sender), msg.value.sub(_priceCost)); } emit NowTokenPrice(tokenAddress,priceInfo.ethAmount, priceInfo.erc20Amount); return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock); } /** * @dev Update and check the latest price-internal use * @param tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Erc20 amount */ function updateAndCheckPricePrivate(address tokenAddress) public view onlyOfferMain returns(uint256 ethAmount, uint256 erc20Amount) { mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = priceInfoList[checkBlock].frontBlock; } if (checkBlock == 0) { return (0,0); } PriceInfo memory priceInfo = priceInfoList[checkBlock]; return (priceInfo.ethAmount,priceInfo.erc20Amount); } /** * @dev Update and check the effective price list * @param tokenAddress Token address * @param num Number of prices to check * @return uint256[] price list */ function updateAndCheckPriceList(address tokenAddress, uint256 num) public payable returns (uint256[] memory) { require(checkUseNestPrice(address(msg.sender))); mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; // Extract data uint256 length = num.mul(3); uint256 index = 0; uint256[] memory data = new uint256[](length); uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(index < length && checkBlock > 0){ if (checkBlock < block.number && priceInfoList[checkBlock].ethAmount != 0) { // Add return data data[index++] = priceInfoList[checkBlock].ethAmount; data[index++] = priceInfoList[checkBlock].erc20Amount; data[index++] = checkBlock; } checkBlock = priceInfoList[checkBlock].frontBlock; } require(length == data.length); // Allocation address nToken = _tokenMapping.checkTokenMapping(tokenAddress); if (nToken == address(0x0)) { _abonus.switchToEth.value(_priceCost)(address(_nestToken)); } else { _abonus.switchToEth.value(_priceCost)(address(nToken)); } if (msg.value > _priceCost) { repayEth(address(msg.sender), msg.value.sub(_priceCost)); } return data; } // Activate the price checking function function activation() public { _nestToken.safeTransferFrom(address(msg.sender), _destructionAddress, destructionAmount); _addressEffect[address(msg.sender)] = now.add(effectTime); } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // Check block price - user account only function checkPriceForBlock(address tokenAddress, uint256 blockNum) public view returns (uint256 ethAmount, uint256 erc20Amount) { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; return (tokenInfo.priceInfoList[blockNum].ethAmount, tokenInfo.priceInfoList[blockNum].erc20Amount); } // Check real-time price - user account only function checkPriceNow(address tokenAddress) public view returns (uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = priceInfoList[checkBlock].frontBlock; } if (checkBlock == 0) { return (0,0,0); } PriceInfo storage priceInfo = priceInfoList[checkBlock]; return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock); } // Check whether the price-checking functions can be called function checkUseNestPrice(address target) public view returns (bool) { if (!_blocklist[target] && _addressEffect[target] < now && _addressEffect[target] != 0) { return true; } else { return false; } } // Check whether the address is in the blocklist function checkBlocklist(address add) public view returns(bool) { return _blocklist[add]; } // Check the amount of NEST to destroy to call prices function checkDestructionAmount() public view returns(uint256) { return destructionAmount; } // Check the waiting time to start calling prices function checkEffectTime() public view returns (uint256) { return effectTime; } // Check call price fee function checkPriceCost() public view returns (uint256) { return _priceCost; } // Modify the blocklist function changeBlocklist(address add, bool isBlock) public onlyOwner { _blocklist[add] = isBlock; } // Amount of NEST to destroy to call price-checking functions function changeDestructionAmount(uint256 amount) public onlyOwner { destructionAmount = amount; } // Modify the waiting time to start calling prices function changeEffectTime(uint256 num) public onlyOwner { effectTime = num; } // Modify call price fee function changePriceCost(uint256 num) public onlyOwner { _priceCost = num; } // Offering contract only modifier onlyOfferMain(){ require(_offerMainMapping[address(msg.sender)], "No authority"); _; } // Vote administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } /** * @title NEST and NToken lock-up contract * @dev NEST and NToken deposit and withdrawal */ contract Nest_3_TokenSave { using SafeMath for uint256; Nest_3_VoteFactory _voteFactory; // Voting contract mapping(address => mapping(address => uint256)) _baseMapping; // Ledger token=>user=>amount /** * @dev initialization method * @param voteFactory Voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Withdrawing * @param num Withdrawing amount * @param token Lock-up token address * @param target Transfer target */ function takeOut(uint256 num, address token, address target) public onlyContract { require(num <= _baseMapping[token][address(target)], "Insufficient storage balance"); _baseMapping[token][address(target)] = _baseMapping[token][address(target)].sub(num); ERC20(token).transfer(address(target), num); } /** * @dev Depositing * @param num Depositing amount * @param token Lock-up token address * @param target Depositing target */ function depositIn(uint256 num, address token, address target) public onlyContract { require(ERC20(token).transferFrom(address(target),address(this),num), "Authorization transfer failed"); _baseMapping[token][address(target)] = _baseMapping[token][address(target)].add(num); } /** * @dev Check the amount * @param sender Check address * @param token Lock-up token address * @return uint256 Check address corresponding lock-up limit */ function checkAmount(address sender, address token) public view returns(uint256) { return _baseMapping[token][address(sender)]; } // Administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } // Only for bonus logic contract modifier onlyContract(){ require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority"); _; } } /** * @title Dividend logic * @dev Some operations about dividend,logic and asset separation */ contract Nest_3_TokenAbonus { using address_make_payable for address; using SafeMath for uint256; ERC20 _nestContract; Nest_3_TokenSave _tokenSave; // Lock-up contract Nest_3_Abonus _abonusContract; // ETH bonus pool Nest_3_VoteFactory _voteFactory; // Voting contract Nest_3_Leveling _nestLeveling; // Leveling contract address _destructionAddress; // Destroy contract address uint256 _timeLimit = 168 hours; // Bonus period uint256 _nextTime = 1596168000; // Next bonus time uint256 _getAbonusTimeLimit = 60 hours; // During of triggering calculation of bonus uint256 _times = 0; // Bonus ledger uint256 _expectedIncrement = 3; // Expected bonus increment ratio uint256 _expectedSpanForNest = 100000000 ether; // NEST expected bonus increment threshold uint256 _expectedSpanForNToken = 1000000 ether; // NToken expected bonus increment threshold uint256 _expectedMinimum = 100 ether; // Expected minimum bonus uint256 _savingLevelOne = 10; // Saving threshold level 1 uint256 _savingLevelTwo = 20; // Saving threshold level 2 uint256 _savingLevelTwoSub = 100 ether; // Function parameters of savings threshold level 2 uint256 _savingLevelThree = 30; // Function parameters of savings threshold level 3 uint256 _savingLevelThreeSub = 600 ether; // Function parameters of savings threshold level 3 mapping(address => uint256) _abonusMapping; // Bonus pool snapshot - token address (NEST or NToken) => number of ETH in the bonus pool mapping(address => uint256) _tokenAllValueMapping; // Number of tokens (circulation) - token address (NEST or NToken) ) => total circulation mapping(address => mapping(uint256 => uint256)) _tokenAllValueHistory; // NEST or NToken circulation snapshot - token address (NEST or NToken) => number of periods => total circulation mapping(address => mapping(uint256 => mapping(address => uint256))) _tokenSelfHistory; // Personal lockup - NEST or NToken snapshot token address (NEST or NToken) => period => user address => total circulation mapping(address => mapping(uint256 => bool)) _snapshot; // Whether snapshot - token address (NEST or NToken) => number of periods => whether to take a snapshot mapping(uint256 => mapping(address => mapping(address => bool))) _getMapping; // Receiving records - period => token address (NEST or NToken) => user address => whether received // Log token address, amount event GetTokenLog(address tokenAddress, uint256 tokenAmount); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _nestContract = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenSave = Nest_3_TokenSave(address(voteFactoryMap.checkAddress("nest.v3.tokenSave"))); address payable addr = address(voteFactoryMap.checkAddress("nest.v3.abonus")).make_payable(); _abonusContract = Nest_3_Abonus(addr); address payable levelingAddr = address(voteFactoryMap.checkAddress("nest.v3.leveling")).make_payable(); _nestLeveling = Nest_3_Leveling(levelingAddr); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); } /** * @dev Modify voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _nestContract = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenSave = Nest_3_TokenSave(address(voteFactoryMap.checkAddress("nest.v3.tokenSave"))); address payable addr = address(voteFactoryMap.checkAddress("nest.v3.abonus")).make_payable(); _abonusContract = Nest_3_Abonus(addr); address payable levelingAddr = address(voteFactoryMap.checkAddress("nest.v3.leveling")).make_payable(); _nestLeveling = Nest_3_Leveling(levelingAddr); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); } /** * @dev Deposit * @param amount Deposited amount * @param token Locked token address */ function depositIn(uint256 amount, address token) public { uint256 nowTime = now; uint256 nextTime = _nextTime; uint256 timeLimit = _timeLimit; if (nowTime < nextTime) { // Bonus triggered require(!(nowTime >= nextTime.sub(timeLimit) && nowTime <= nextTime.sub(timeLimit).add(_getAbonusTimeLimit))); } else { // Bonus not triggered uint256 times = (nowTime.sub(_nextTime)).div(_timeLimit); // Calculate the time when bonus should be started uint256 startTime = _nextTime.add((times).mul(_timeLimit)); // Calculate the time when bonus should be stopped uint256 endTime = startTime.add(_getAbonusTimeLimit); require(!(nowTime >= startTime && nowTime <= endTime)); } _tokenSave.depositIn(amount, token, address(msg.sender)); } /** * @dev Withdrawing * @param amount Withdrawing amount * @param token Token address */ function takeOut(uint256 amount, address token) public { require(amount > 0, "Parameter needs to be greater than 0"); require(amount <= _tokenSave.checkAmount(address(msg.sender), token), "Insufficient storage balance"); if (token == address(_nestContract)) { require(!_voteFactory.checkVoteNow(address(tx.origin)), "Voting"); } _tokenSave.takeOut(amount, token, address(msg.sender)); } /** * @dev Receiving * @param token Receiving token address */ function getAbonus(address token) public { uint256 tokenAmount = _tokenSave.checkAmount(address(msg.sender), token); require(tokenAmount > 0, "Insufficient storage balance"); reloadTime(); reloadToken(token); uint256 nowTime = now; require(nowTime >= _nextTime.sub(_timeLimit) && nowTime <= _nextTime.sub(_timeLimit).add(_getAbonusTimeLimit), "Not time to draw"); require(!_getMapping[_times.sub(1)][token][address(msg.sender)], "Have received"); _tokenSelfHistory[token][_times.sub(1)][address(msg.sender)] = tokenAmount; require(_tokenAllValueMapping[token] > 0, "Total flux error"); uint256 selfNum = tokenAmount.mul(_abonusMapping[token]).div(_tokenAllValueMapping[token]); require(selfNum > 0, "No limit available"); _getMapping[_times.sub(1)][token][address(msg.sender)] = true; _abonusContract.getETH(selfNum, token,address(msg.sender)); emit GetTokenLog(token, selfNum); } /** * @dev Update bonus time and stage ledger */ function reloadTime() private { uint256 nowTime = now; // The current time must exceed the bonus time if (nowTime >= _nextTime) { uint256 time = (nowTime.sub(_nextTime)).div(_timeLimit); uint256 startTime = _nextTime.add((time).mul(_timeLimit)); uint256 endTime = startTime.add(_getAbonusTimeLimit); if (nowTime >= startTime && nowTime <= endTime) { _nextTime = getNextTime(); _times = _times.add(1); } } } /** * @dev Snapshot of the amount of tokens * @param token Receiving token address */ function reloadToken(address token) private { if (!_snapshot[token][_times.sub(1)]) { levelingResult(token); _abonusMapping[token] = _abonusContract.getETHNum(token); _tokenAllValueMapping[token] = allValue(token); _tokenAllValueHistory[token][_times.sub(1)] = allValue(token); _snapshot[token][_times.sub(1)] = true; } } /** * @dev Leveling settlement * @param token Receiving token address */ function levelingResult(address token) private { uint256 steps; if (token == address(_nestContract)) { steps = allValue(token).div(_expectedSpanForNest); } else { steps = allValue(token).div(_expectedSpanForNToken); } uint256 minimumAbonus = _expectedMinimum; for (uint256 i = 0; i < steps; i++) { minimumAbonus = minimumAbonus.add(minimumAbonus.mul(_expectedIncrement).div(100)); } uint256 thisAbonus = _abonusContract.getETHNum(token); if (thisAbonus > minimumAbonus) { uint256 levelAmount = 0; if (thisAbonus > 5000 ether) { levelAmount = thisAbonus.mul(_savingLevelThree).div(100).sub(_savingLevelThreeSub); } else if (thisAbonus > 1000 ether) { levelAmount = thisAbonus.mul(_savingLevelTwo).div(100).sub(_savingLevelTwoSub); } else { levelAmount = thisAbonus.mul(_savingLevelOne).div(100); } if (thisAbonus.sub(levelAmount) < minimumAbonus) { _abonusContract.getETH(thisAbonus.sub(minimumAbonus), token, address(this)); _nestLeveling.switchToEth.value(thisAbonus.sub(minimumAbonus))(token); } else { _abonusContract.getETH(levelAmount, token, address(this)); _nestLeveling.switchToEth.value(levelAmount)(token); } } else { uint256 ethValue = _nestLeveling.tranEth(minimumAbonus.sub(thisAbonus), token, address(this)); _abonusContract.switchToEth.value(ethValue)(token); } } // Next bonus time, current bonus deadline, ETH number, NEST number, NEST participating in bonus, bonus to receive, approved amount, balance, whether bonus can be paid function getInfo(address token) public view returns (uint256 nextTime, uint256 getAbonusTime, uint256 ethNum, uint256 tokenValue, uint256 myJoinToken, uint256 getEth, uint256 allowNum, uint256 leftNum, bool allowAbonus) { uint256 nowTime = now; if (nowTime >= _nextTime.sub(_timeLimit) && nowTime <= _nextTime.sub(_timeLimit).add(_getAbonusTimeLimit) && _times > 0 && _snapshot[token][_times.sub(1)]) { // Bonus have been triggered, and during the time of this bonus, display snapshot data allowAbonus = _getMapping[_times.sub(1)][token][address(msg.sender)]; ethNum = _abonusMapping[token]; tokenValue = _tokenAllValueMapping[token]; } else { // Display real-time data ethNum = _abonusContract.getETHNum(token); tokenValue = allValue(token); allowAbonus = _getMapping[_times][token][address(msg.sender)]; } myJoinToken = _tokenSave.checkAmount(address(msg.sender), token); if (allowAbonus == true) { getEth = 0; } else { getEth = myJoinToken.mul(ethNum).div(tokenValue); } nextTime = getNextTime(); getAbonusTime = nextTime.sub(_timeLimit).add(_getAbonusTimeLimit); allowNum = ERC20(token).allowance(address(msg.sender), address(_tokenSave)); leftNum = ERC20(token).balanceOf(address(msg.sender)); } /** * @dev View next bonus time * @return Next bonus time */ function getNextTime() public view returns (uint256) { uint256 nowTime = now; if (_nextTime > nowTime) { return _nextTime; } else { uint256 time = (nowTime.sub(_nextTime)).div(_timeLimit); return _nextTime.add(_timeLimit.mul(time.add(1))); } } /** * @dev View total circulation * @return Total circulation */ function allValue(address token) public view returns (uint256) { if (token == address(_nestContract)) { uint256 all = 10000000000 ether; uint256 leftNum = all.sub(_nestContract.balanceOf(address(_voteFactory.checkAddress("nest.v3.miningSave")))).sub(_nestContract.balanceOf(address(_destructionAddress))); return leftNum; } else { return ERC20(token).totalSupply(); } } /** * @dev View bonus period * @return Bonus period */ function checkTimeLimit() public view returns (uint256) { return _timeLimit; } /** * @dev View duration of triggering calculation of bonus * @return Bonus period */ function checkGetAbonusTimeLimit() public view returns (uint256) { return _getAbonusTimeLimit; } /** * @dev View current lowest expected bonus * @return Current lowest expected bonus */ function checkMinimumAbonus(address token) public view returns (uint256) { uint256 miningAmount; if (token == address(_nestContract)) { miningAmount = allValue(token).div(_expectedSpanForNest); } else { miningAmount = allValue(token).div(_expectedSpanForNToken); } uint256 minimumAbonus = _expectedMinimum; for (uint256 i = 0; i < miningAmount; i++) { minimumAbonus = minimumAbonus.add(minimumAbonus.mul(_expectedIncrement).div(100)); } return minimumAbonus; } /** * @dev Check whether the bonus token is snapshoted * @param token Token address * @return Whether snapshoted */ function checkSnapshot(address token) public view returns (bool) { return _snapshot[token][_times.sub(1)]; } /** * @dev Check the expected bonus incremental ratio * @return Expected bonus increment ratio */ function checkeExpectedIncrement() public view returns (uint256) { return _expectedIncrement; } /** * @dev View expected minimum bonus * @return Expected minimum bonus */ function checkExpectedMinimum() public view returns (uint256) { return _expectedMinimum; } /** * @dev View savings threshold * @return Save threshold */ function checkSavingLevelOne() public view returns (uint256) { return _savingLevelOne; } function checkSavingLevelTwo() public view returns (uint256) { return _savingLevelTwo; } function checkSavingLevelThree() public view returns (uint256) { return _savingLevelThree; } /** * @dev View NEST liquidity snapshot * @param token Locked token address * @param times Bonus snapshot period */ function checkTokenAllValueHistory(address token, uint256 times) public view returns (uint256) { return _tokenAllValueHistory[token][times]; } /** * @dev View personal lock-up NEST snapshot * @param times Bonus snapshot period * @param user User address * @return The number of personal locked NEST snapshots */ function checkTokenSelfHistory(address token, uint256 times, address user) public view returns (uint256) { return _tokenSelfHistory[token][times][user]; } // View the period number of bonus function checkTimes() public view returns (uint256) { return _times; } // NEST expected bonus increment threshold function checkExpectedSpanForNest() public view returns (uint256) { return _expectedSpanForNest; } // NToken expected bonus increment threshold function checkExpectedSpanForNToken() public view returns (uint256) { return _expectedSpanForNToken; } // View the function parameters of savings threshold level 3 function checkSavingLevelTwoSub() public view returns (uint256) { return _savingLevelTwoSub; } // View the function parameters of savings threshold level 3 function checkSavingLevelThreeSub() public view returns (uint256) { return _savingLevelThreeSub; } /** * @dev Update bonus period * @param hour Bonus period (hours) */ function changeTimeLimit(uint256 hour) public onlyOwner { require(hour > 0, "Parameter needs to be greater than 0"); _timeLimit = hour.mul(1 hours); } /** * @dev Update collection period * @param hour Collection period (hours) */ function changeGetAbonusTimeLimit(uint256 hour) public onlyOwner { require(hour > 0, "Parameter needs to be greater than 0"); _getAbonusTimeLimit = hour; } /** * @dev Update expected bonus increment ratio * @param num Expected bonus increment ratio */ function changeExpectedIncrement(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _expectedIncrement = num; } /** * @dev Update expected minimum bonus * @param num Expected minimum bonus */ function changeExpectedMinimum(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _expectedMinimum = num; } /** * @dev Update saving threshold * @param threshold Saving threshold */ function changeSavingLevelOne(uint256 threshold) public onlyOwner { _savingLevelOne = threshold; } function changeSavingLevelTwo(uint256 threshold) public onlyOwner { _savingLevelTwo = threshold; } function changeSavingLevelThree(uint256 threshold) public onlyOwner { _savingLevelThree = threshold; } /** * @dev Update the function parameters of savings threshold level 2 */ function changeSavingLevelTwoSub(uint256 num) public onlyOwner { _savingLevelTwoSub = num; } /** * @dev Update the function parameters of savings threshold level 3 */ function changeSavingLevelThreeSub(uint256 num) public onlyOwner { _savingLevelThreeSub = num; } /** * @dev Update NEST expected bonus incremental threshold * @param num Threshold */ function changeExpectedSpanForNest(uint256 num) public onlyOwner { _expectedSpanForNest = num; } /** * @dev Update NToken expected bonus incremental threshold * @param num Threshold */ function changeExpectedSpanForNToken(uint256 num) public onlyOwner { _expectedSpanForNToken = num; } receive() external payable { } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } } /** * @title ETH bonus pool * @dev ETH collection and inquiry */ contract Nest_3_Abonus { using address_make_payable for address; using SafeMath for uint256; Nest_3_VoteFactory _voteFactory; // Voting contract address _nestAddress; // NEST contract address mapping (address => uint256) ethMapping; // ETH bonus ledger of corresponding tokens uint256 _mostDistribution = 40; // The highest allocation ratio of NEST bonus pool uint256 _leastDistribution = 20; // The lowest allocation ratio of NEST bonus pool uint256 _distributionTime = 1200000; // The decay time interval of NEST bonus pool allocation ratio uint256 _distributionSpan = 5; // The decay degree of NEST bonus pool allocation ratio /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(voteFactory); _nestAddress = address(_voteFactory.checkAddress("nest")); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner{ _voteFactory = Nest_3_VoteFactory(voteFactory); _nestAddress = address(_voteFactory.checkAddress("nest")); } /** * @dev Transfer in bonus * @param token Corresponding to lock-up Token */ function switchToEth(address token) public payable { ethMapping[token] = ethMapping[token].add(msg.value); } /** * @dev Transferin bonus - NToken offering fee * @param token Corresponding to lock-up NToken */ function switchToEthForNTokenOffer(address token) public payable { Nest_NToken nToken = Nest_NToken(token); (uint256 createBlock,) = nToken.checkBlockInfo(); uint256 subBlock = block.number.sub(createBlock); uint256 times = subBlock.div(_distributionTime); uint256 distributionValue = times.mul(_distributionSpan); uint256 distribution = _mostDistribution; if (_leastDistribution.add(distributionValue) > _mostDistribution) { distribution = _leastDistribution; } else { distribution = _mostDistribution.sub(distributionValue); } uint256 nestEth = msg.value.mul(distribution).div(100); ethMapping[_nestAddress] = ethMapping[_nestAddress].add(nestEth); ethMapping[token] = ethMapping[token].add(msg.value.sub(nestEth)); } /** * @dev Receive ETH * @param num Receive amount * @param token Correspond to locked Token * @param target Transfer target */ function getETH(uint256 num, address token, address target) public onlyContract { require(num <= ethMapping[token], "Insufficient storage balance"); ethMapping[token] = ethMapping[token].sub(num); address payable addr = target.make_payable(); addr.transfer(num); } /** * @dev Get bonus pool balance * @param token Corresponded locked Token * @return uint256 Bonus pool balance */ function getETHNum(address token) public view returns (uint256) { return ethMapping[token]; } // View NEST address function checkNestAddress() public view returns(address) { return _nestAddress; } // View the highest NEST bonus pool allocation ratio function checkMostDistribution() public view returns(uint256) { return _mostDistribution; } // View the lowest NEST bonus pool allocation ratio function checkLeastDistribution() public view returns(uint256) { return _leastDistribution; } // View the decay time interval of NEST bonus pool allocation ratio function checkDistributionTime() public view returns(uint256) { return _distributionTime; } // View the decay degree of NEST bonus pool allocation ratio function checkDistributionSpan() public view returns(uint256) { return _distributionSpan; } // Modify the highest NEST bonus pool allocation ratio function changeMostDistribution(uint256 num) public onlyOwner { _mostDistribution = num; } // Modify the lowest NEST bonus pool allocation ratio function changeLeastDistribution(uint256 num) public onlyOwner { _leastDistribution = num; } // Modify the decay time interval of NEST bonus pool allocation ratio function changeDistributionTime(uint256 num) public onlyOwner { _distributionTime = num; } // Modify the decay degree of NEST bonus pool allocation ratio function changeDistributionSpan(uint256 num) public onlyOwner { _distributionSpan = num; } // Withdraw ETH function turnOutAllEth(uint256 amount, address target) public onlyOwner { address payable addr = target.make_payable(); addr.transfer(amount); } // Only bonus logic contract modifier onlyContract(){ require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority"); _; } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } } /** * @title Leveling contract * @dev ETH transfer in and transfer out */ contract Nest_3_Leveling { using address_make_payable for address; using SafeMath for uint256; Nest_3_VoteFactory _voteFactory; // Vote contract mapping (address => uint256) ethMapping; // Corresponded ETH leveling ledger of token /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Modifying voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Transfer out leveling * @param amount Transfer-out amount * @param token Corresponding lock-up token * @param target Transfer-out target */ function tranEth(uint256 amount, address token, address target) public returns (uint256) { require(address(msg.sender) == address(_voteFactory.checkAddress("nest.v3.tokenAbonus")), "No authority"); uint256 tranAmount = amount; if (tranAmount > ethMapping[token]) { tranAmount = ethMapping[token]; } ethMapping[token] = ethMapping[token].sub(tranAmount); address payable addr = target.make_payable(); addr.transfer(tranAmount); return tranAmount; } /** * @dev Transfer in leveling * @param token Corresponded locked token */ function switchToEth(address token) public payable { ethMapping[token] = ethMapping[token].add(msg.value); } // Check the leveled amount corresponding to the token function checkEthMapping(address token) public view returns (uint256) { return ethMapping[token]; } // Withdraw ETH function turnOutAllEth(uint256 amount, address target) public onlyOwner { address payable addr = target.make_payable(); addr.transfer(amount); } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } } /** * @title Offering contract * @dev Offering logic and mining logic */ contract Nest_NToken_OfferMain { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; // Offering data structure struct Nest_NToken_OfferPriceData { // The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress()) address owner; // Offering owner bool deviate; // Whether it deviates address tokenAddress; // The erc20 contract address of the target offer token uint256 ethAmount; // The ETH amount in the offer list uint256 tokenAmount; // The token amount in the offer list uint256 dealEthAmount; // The remaining number of tradable ETH uint256 dealTokenAmount; // The remaining number of tradable tokens uint256 blockNum; // The block number where the offer is located uint256 serviceCharge; // The fee for mining // Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0 } Nest_NToken_OfferPriceData [] _prices; // Array used to save offers Nest_3_VoteFactory _voteFactory; // Voting contract Nest_3_OfferPrice _offerPrice; // Price contract Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract ERC20 _nestToken; // nestToken Nest_3_Abonus _abonus; // Bonus pool uint256 _miningETH = 10; // Offering mining fee ratio uint256 _tranEth = 1; // Taker fee ratio uint256 _tranAddition = 2; // Additional transaction multiple uint256 _leastEth = 10 ether; // Minimum offer of ETH uint256 _offerSpan = 10 ether; // ETH Offering span uint256 _deviate = 10; // Price deviation - 10% uint256 _deviationFromScale = 10; // Deviation from asset scale uint256 _ownerMining = 5; // Creator ratio uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount uint32 _blockLimit = 25; // Block interval upper limit uint256 _blockAttenuation = 2400000; // Block decay interval mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount uint256[10] _attenuationAmount; // Mining decay list // Log token contract address event OfferTokenContractAddress(address contractAddress); // Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining); // Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); // Log current block, current block mined amount, token address event OreDrawingLog(uint256 nowBlock, uint256 blockAmount, address tokenAddress); // Log offering block, token address, token offered times event MiningLog(uint256 blockNum, address tokenAddress, uint256 offerTimes); /** * Initialization method * @param voteFactory Voting contract address **/ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); uint256 blockAmount = 4 ether; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(8).div(10); } } /** * Reset voting contract method * @param voteFactory Voting contract address **/ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); } /** * Offering method * @param ethAmount ETH amount * @param erc20Amount Erc20 token amount * @param erc20Address Erc20 token address **/ function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); address nTokenAddress = _tokenMapping.checkTokenMapping(erc20Address); require(nTokenAddress != address(0x0)); // Judge whether the price deviates uint256 ethMining; bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address); if (isDeviate) { require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale"); ethMining = _leastEth.mul(_miningETH).div(1000); } else { ethMining = ethAmount.mul(_miningETH).div(1000); } require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee"); uint256 subValue = msg.value.sub(ethAmount.add(ethMining)); if (subValue > 0) { repayEth(address(msg.sender), subValue); } // Create an offer createOffer(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining); // Transfer in offer asset - erc20 to this contract ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount); _abonus.switchToEthForNTokenOffer.value(ethMining)(nTokenAddress); // Mining if (_blockOfferAmount[block.number][erc20Address] == 0) { uint256 miningAmount = oreDrawing(nTokenAddress); Nest_NToken nToken = Nest_NToken(nTokenAddress); nToken.transfer(nToken.checkBidder(), miningAmount.mul(_ownerMining).div(100)); _blockMining[block.number][erc20Address] = miningAmount.sub(miningAmount.mul(_ownerMining).div(100)); } _blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].add(ethMining); } /** * @dev Create offer * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 amount * @param erc20Address Offering erc20 address **/ function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private { // Check offer conditions require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0); // Create offering contract emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining); _prices.push(Nest_NToken_OfferPriceData( msg.sender, isDeviate, erc20Address, ethAmount, erc20Amount, ethAmount, erc20Amount, block.number, mining )); // Record price _offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender)); } // Convert offer address into index in offer array function toIndex(address contractAddress) public pure returns(uint256) { return uint256(contractAddress); } // Convert index in offer array into offer address function toAddress(uint256 index) public pure returns(address) { return address(index); } /** * Withdraw offer assets * @param contractAddress Offer address **/ function turnOut(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData storage offerPriceData = _prices[index]; require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error"); // Withdraw ETH if (offerPriceData.ethAmount > 0) { uint256 payEth = offerPriceData.ethAmount; offerPriceData.ethAmount = 0; repayEth(offerPriceData.owner, payEth); } // Withdraw erc20 if (offerPriceData.tokenAmount > 0) { uint256 payErc = offerPriceData.tokenAmount; offerPriceData.tokenAmount = 0; ERC20(address(offerPriceData.tokenAddress)).safeTransfer(address(offerPriceData.owner), payErc); } // Mining settlement if (offerPriceData.serviceCharge > 0) { mining(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner); offerPriceData.serviceCharge = 0; } } /** * @dev Taker order - pay ETH and buy erc20 * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract if (tokenAmount > tranTokenAmount) { ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount)); } else { ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount)); } // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress); _abonus.switchToEth.value(serviceCharge)(nTokenAddress); } } /** * @dev Taker order - pay erc20 and buy ETH * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount)); // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress); _abonus.switchToEth.value(serviceCharge)(nTokenAddress); } } /** * Offering mining * @param ntoken NToken address **/ function oreDrawing(address ntoken) private returns(uint256) { Nest_NToken miningToken = Nest_NToken(ntoken); (uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.checkBlockInfo(); uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation); uint256 miningAmount = 0; uint256 attenuation; if (attenuationPointNow > 9) { attenuation = _afterMiningAmount; } else { attenuation = _attenuationAmount[attenuationPointNow]; } miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock)); miningToken.increaseTotal(miningAmount); emit OreDrawingLog(block.number, miningAmount, ntoken); return miningAmount; } /** * Retrieve mining * @param token Token address **/ function mining(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) { // Block mining amount*offer fee/block offer fee uint256 miningAmount = _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]); // Transfer NToken Nest_NToken nToken = Nest_NToken(address(_tokenMapping.checkTokenMapping(token))); require(nToken.transfer(address(owner), miningAmount), "Transfer failure"); emit MiningLog(blockNum, token,_blockOfferAmount[blockNum][token]); return miningAmount; } // Compare order prices function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { (uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token); if (frontEthValue == 0 || frontTokenValue == 0) { return false; } uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue <= maxTokenAmount) { uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue >= minTokenAmount) { return false; } } return true; } // Check contract status function checkContractState(uint256 createBlock) public view returns (uint256) { if (block.number.sub(createBlock) > _blockLimit) { return 1; } return 0; } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // View the upper limit of the block interval function checkBlockLimit() public view returns(uint256) { return _blockLimit; } // View taker fee ratio function checkTranEth() public view returns (uint256) { return _tranEth; } // View additional transaction multiple function checkTranAddition() public view returns(uint256) { return _tranAddition; } // View minimum offering ETH function checkleastEth() public view returns(uint256) { return _leastEth; } // View offering ETH span function checkOfferSpan() public view returns(uint256) { return _offerSpan; } // View block offering amount function checkBlockOfferAmount(uint256 blockNum, address token) public view returns (uint256) { return _blockOfferAmount[blockNum][token]; } // View offering block mining amount function checkBlockMining(uint256 blockNum, address token) public view returns (uint256) { return _blockMining[blockNum][token]; } // View offering mining amount function checkOfferMining(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) { if (serviceCharge == 0) { return 0; } else { return _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]); } } // View the owner allocation ratio function checkOwnerMining() public view returns(uint256) { return _ownerMining; } // View the mining decay function checkAttenuationAmount(uint256 num) public view returns(uint256) { return _attenuationAmount[num]; } // Modify taker order fee ratio function changeTranEth(uint256 num) public onlyOwner { _tranEth = num; } // Modify block interval upper limit function changeBlockLimit(uint32 num) public onlyOwner { _blockLimit = num; } // Modify additional transaction multiple function changeTranAddition(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _tranAddition = num; } // Modify minimum offering ETH function changeLeastEth(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _leastEth = num; } // Modify offering ETH span function changeOfferSpan(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _offerSpan = num; } // Modify price deviation function changekDeviate(uint256 num) public onlyOwner { _deviate = num; } // Modify the deviation from scale function changeDeviationFromScale(uint256 num) public onlyOwner { _deviationFromScale = num; } // Modify the owner allocation ratio function changeOwnerMining(uint256 num) public onlyOwner { _ownerMining = num; } // Modify the mining decay function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner { uint256 blockAmount = firstAmount; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(top).div(bottom); } } // Vote administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } /** * Get the number of offers stored in the offer array * @return The number of offers stored in the offer array **/ function getPriceCount() view public returns (uint256) { return _prices.length; } /** * Get offer information according to the index * @param priceIndex Offer index * @return Offer information **/ function getPrice(uint256 priceIndex) view public returns (string memory) { // The buffer array used to generate the result string bytes memory buf = new bytes(500000); uint256 index = 0; index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index); // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Search the contract address list of the target account (reverse order) * @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address) * @param count Maximum number of records to return * @param maxFindCount The max index to search * @param owner Target account address * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Calculate search interval i and end uint256 i = _prices.length; uint256 end = 0; if (start != address(0)) { i = toIndex(start); } if (i > maxFindCount) { end = i - maxFindCount; } // Loop search, write qualified records into buffer while (count > 0 && i-- > end) { Nest_NToken_OfferPriceData memory price = _prices[i]; if (price.owner == owner) { --count; index = writeOfferPriceData(i, price, buf, index); } } // Generate result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Get the list of offers by page * @param offset Skip the first offset records * @param count Maximum number of records to return * @param order Sort rules. 0 means reverse order, non-zero means positive order * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Find search interval i and end uint256 i = 0; uint256 end = 0; if (order == 0) { // Reverse order, in default // Calculate search interval i and end if (offset < _prices.length) { i = _prices.length - offset; } if (count < i) { end = i - count; } // Write records in the target interval into the buffer while (i-- > end) { index = writeOfferPriceData(i, _prices[i], buf, index); } } else { // Ascending order // Calculate the search interval i and end if (offset < _prices.length) { i = offset; } else { i = _prices.length; } end = i + count; if(end > _prices.length) { end = _prices.length; } // Write the records in the target interval into the buffer while (i < end) { index = writeOfferPriceData(i, _prices[i], buf, index); ++i; } } // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } // Write the offer data into the buffer and return the buffer index function writeOfferPriceData(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { index = writeAddress(toAddress(priceIndex), buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.owner, buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.tokenAddress, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.ethAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.tokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealEthAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealTokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.blockNum, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.serviceCharge, buf, index); buf[index++] = byte(uint8(44)); return index; } // Convert integer to string in decimal form, write the string into the buffer, and return the buffer index function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { uint256 i = index; do { buf[index++] = byte(uint8(iv % 10 +48)); iv /= 10; } while (iv > 0); for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { uint256 iv = uint256(addr); uint256 i = index + 40; do { uint256 w = iv % 16; if(w < 10) { buf[index++] = byte(uint8(w +48)); } else { buf[index++] = byte(uint8(w +87)); } iv /= 16; } while (index < i); i -= 40; for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } } /** * @title Auction NToken contract * @dev Auction for listing and generating NToken */ contract Nest_NToken_TokenAuction { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; Nest_3_VoteFactory _voteFactory; // Voting contract Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract ERC20 _nestToken; // NestToken Nest_3_OfferPrice _offerPrice; // Price contract address _destructionAddress; // Destruction contract address uint256 _duration = 5 days; // Auction duration uint256 _minimumNest = 100000 ether; // Minimum auction amount uint256 _tokenNum = 1; // Auction token number uint256 _incentiveRatio = 50; // Incentive ratio uint256 _minimumInterval = 10000 ether; // Minimum auction interval mapping(address => AuctionInfo) _auctionList; // Auction list mapping(address => bool) _tokenBlackList; // Auction blacklist struct AuctionInfo { uint256 endTime; // End time uint256 auctionValue; // Auction price address latestAddress; // Highest auctioneer uint256 latestAmount; // Lastest auction amount } address[] _allAuction; // Auction list array /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); } /** * @dev Initiating auction * @param token Auction token address * @param auctionAmount Initial auction amount */ function startAnAuction(address token, uint256 auctionAmount) public { require(_tokenMapping.checkTokenMapping(token) == address(0x0), "Token already exists"); require(_auctionList[token].endTime == 0, "Token is on sale"); require(auctionAmount >= _minimumNest, "AuctionAmount less than the minimum auction amount"); require(_nestToken.transferFrom(address(msg.sender), address(this), auctionAmount), "Authorization failed"); require(!_tokenBlackList[token]); // Verification ERC20 tokenERC20 = ERC20(token); tokenERC20.safeTransferFrom(address(msg.sender), address(this), 1); require(tokenERC20.balanceOf(address(this)) >= 1); tokenERC20.safeTransfer(address(msg.sender), 1); AuctionInfo memory thisAuction = AuctionInfo(now.add(_duration), auctionAmount, address(msg.sender), auctionAmount); _auctionList[token] = thisAuction; _allAuction.push(token); } /** * @dev Auction * @param token Auction token address * @param auctionAmount Auction amount */ function continueAuction(address token, uint256 auctionAmount) public { require(now <= _auctionList[token].endTime && _auctionList[token].endTime != 0, "Auction closed"); require(auctionAmount > _auctionList[token].auctionValue, "Insufficient auction amount"); uint256 subAuctionAmount = auctionAmount.sub(_auctionList[token].auctionValue); require(subAuctionAmount >= _minimumInterval); uint256 excitation = subAuctionAmount.mul(_incentiveRatio).div(100); require(_nestToken.transferFrom(address(msg.sender), address(this), auctionAmount), "Authorization failed"); require(_nestToken.transfer(_auctionList[token].latestAddress, _auctionList[token].auctionValue.add(excitation)), "Transfer failure"); // Update auction information _auctionList[token].auctionValue = auctionAmount; _auctionList[token].latestAddress = address(msg.sender); _auctionList[token].latestAmount = _auctionList[token].latestAmount.add(subAuctionAmount.sub(excitation)); } /** * @dev Listing * @param token Auction token address */ function auctionSuccess(address token) public { Nest_3_TokenAbonus nestAbonus = Nest_3_TokenAbonus(payable(_voteFactory.checkAddress("nest.v3.tokenAbonus"))); uint256 nowTime = now; uint256 nextTime = nestAbonus.getNextTime(); uint256 timeLimit = nestAbonus.checkTimeLimit(); uint256 getAbonusTimeLimit = nestAbonus.checkGetAbonusTimeLimit(); require(!(nowTime >= nextTime.sub(timeLimit) && nowTime <= nextTime.sub(timeLimit).add(getAbonusTimeLimit)), "Not time to auctionSuccess"); require(nowTime > _auctionList[token].endTime && _auctionList[token].endTime != 0, "Token is on sale"); // Initialize NToken Nest_NToken nToken = new Nest_NToken(strConcat("NToken", getAddressStr(_tokenNum)), strConcat("N", getAddressStr(_tokenNum)), address(_voteFactory), address(_auctionList[token].latestAddress)); // Auction NEST destruction require(_nestToken.transfer(_destructionAddress, _auctionList[token].latestAmount), "Transfer failure"); // Add NToken mapping _tokenMapping.addTokenMapping(token, address(nToken)); // Initialize charging parameters _offerPrice.addPriceCost(token); _tokenNum = _tokenNum.add(1); } function strConcat(string memory _a, string memory _b) public pure returns (string memory){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ret = new string(_ba.length + _bb.length); bytes memory bret = bytes(ret); uint k = 0; for (uint i = 0; i < _ba.length; i++) { bret[k++] = _ba[i]; } for (uint i = 0; i < _bb.length; i++) { bret[k++] = _bb[i]; } return string(ret); } // Convert to 4-digit string function getAddressStr(uint256 iv) public pure returns (string memory) { bytes memory buf = new bytes(64); uint256 index = 0; do { buf[index++] = byte(uint8(iv % 10 + 48)); iv /= 10; } while (iv > 0 || index < 4); bytes memory str = new bytes(index); for(uint256 i = 0; i < index; ++i) { str[i] = buf[index - i - 1]; } return string(str); } // Check auction duration function checkDuration() public view returns(uint256) { return _duration; } // Check minimum auction amount function checkMinimumNest() public view returns(uint256) { return _minimumNest; } // Check initiated number of auction tokens function checkAllAuctionLength() public view returns(uint256) { return _allAuction.length; } // View auctioned token addresses function checkAuctionTokenAddress(uint256 num) public view returns(address) { return _allAuction[num]; } // View auction blacklist function checkTokenBlackList(address token) public view returns(bool) { return _tokenBlackList[token]; } // View auction token information function checkAuctionInfo(address token) public view returns(uint256 endTime, uint256 auctionValue, address latestAddress) { AuctionInfo memory info = _auctionList[token]; return (info.endTime, info.auctionValue, info.latestAddress); } // View token number function checkTokenNum() public view returns (uint256) { return _tokenNum; } // Modify auction duration function changeDuration(uint256 num) public onlyOwner { _duration = num.mul(1 days); } // Modify minimum auction amount function changeMinimumNest(uint256 num) public onlyOwner { _minimumNest = num; } // Modify auction blacklist function changeTokenBlackList(address token, bool isBlack) public onlyOwner { _tokenBlackList[token] = isBlack; } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } contract Nest_NToken is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; // Balance ledger mapping (address => mapping (address => uint256)) private _allowed; // Approval ledger uint256 private _totalSupply = 0 ether; // Total supply string public name; // Token name string public symbol; // Token symbol uint8 public decimals = 18; // Precision uint256 public _createBlock; // Create block number uint256 public _recentlyUsedBlock; // Recently used block number Nest_3_VoteFactory _voteFactory; // Voting factory contract address _bidder; // Owner /** * @dev Initialization method * @param _name Token name * @param _symbol Token symbol * @param voteFactory Voting factory contract address * @param bidder Successful bidder address */ constructor (string memory _name, string memory _symbol, address voteFactory, address bidder) public { name = _name; symbol = _symbol; _createBlock = block.number; _recentlyUsedBlock = block.number; _voteFactory = Nest_3_VoteFactory(address(voteFactory)); _bidder = bidder; } /** * @dev Reset voting contract method * @param voteFactory Voting contract address */ function changeMapping (address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); } /** * @dev Additional issuance * @param value Additional issuance amount */ function increaseTotal(uint256 value) public { address offerMain = address(_voteFactory.checkAddress("nest.nToken.offerMain")); require(address(msg.sender) == offerMain, "No authority"); _balances[offerMain] = _balances[offerMain].add(value); _totalSupply = _totalSupply.add(value); _recentlyUsedBlock = block.number; } /** * @dev Check the total amount of tokens * @return Total supply */ function totalSupply() override public view returns (uint256) { return _totalSupply; } /** * @dev Check address balance * @param owner Address to be checked * @return Return the balance of the corresponding address */ function balanceOf(address owner) override public view returns (uint256) { return _balances[owner]; } /** * @dev Check block information * @return createBlock Initial block number * @return recentlyUsedBlock Recently mined and issued block */ function checkBlockInfo() public view returns(uint256 createBlock, uint256 recentlyUsedBlock) { return (_createBlock, _recentlyUsedBlock); } /** * @dev Check owner's approved allowance to the spender * @param owner Approving address * @param spender Approved address * @return Approved amount */ function allowance(address owner, address spender) override public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer method * @param to Transfer target * @param value Transfer amount * @return Whether the transfer is successful */ function transfer(address to, uint256 value) override public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approval method * @param spender Approval target * @param value Approval amount * @return Whether the approval is successful */ function approve(address spender, uint256 value) override public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens when approved * @param from Transfer-out account address * @param to Transfer-in account address * @param value Transfer amount * @return Whether approved transfer is successful */ function transferFrom(address from, address to, uint256 value) override public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the allowance * @param spender Approval target * @param addedValue Amount to increase * @return whether increase is successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the allowance * @param spender Approval target * @param subtractedValue Amount to decrease * @return Whether decrease is successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer method * @param to Transfer target * @param value Transfer amount */ function _transfer(address from, address to, uint256 value) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Check the creator * @return Creator address */ function checkBidder() public view returns(address) { return _bidder; } /** * @dev Transfer creator * @param bidder New creator address */ function changeBidder(address bidder) public { require(address(msg.sender) == _bidder); _bidder = bidder; } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender)); _; } } /** * @title NToken mapping contract * @dev Add, modify and check offering token mapping */ contract Nest_NToken_TokenMapping { mapping (address => address) _tokenMapping; // Token mapping - offering token => NToken Nest_3_VoteFactory _voteFactory; // Voting contract event TokenMappingLog(address token, address nToken); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); } /** * @dev Reset voting contract * @param voteFactory voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); } /** * @dev Add token mapping * @param token Offering token address * @param nToken Mining NToken address */ function addTokenMapping(address token, address nToken) public { require(address(msg.sender) == address(_voteFactory.checkAddress("nest.nToken.tokenAuction")), "No authority"); require(_tokenMapping[token] == address(0x0), "Token already exists"); _tokenMapping[token] = nToken; emit TokenMappingLog(token, nToken); } /** * @dev Change token mapping * @param token Offering token address * @param nToken Mining NToken address */ function changeTokenMapping(address token, address nToken) public onlyOwner { _tokenMapping[token] = nToken; emit TokenMappingLog(token, nToken); } /** * @dev Check token mapping * @param token Offering token address * @return Mining NToken address */ function checkTokenMapping(address token) public view returns (address) { return _tokenMapping[token]; } // Only for administrator modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } }
Minimum auction amount
uint256 _minimumNest = 100000 ether;
12,580,456
[ 1, 13042, 279, 4062, 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, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 389, 15903, 50, 395, 273, 25259, 225, 2437, 31, 7682, 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/83/0x684E7317C9e823CAbcA4dDf998AB019Dbe85F17F/sources/contracts/CToken/CEther.sol
* @notice Construct a new CEther money market @param comptroller_ The address of the Comptroller @param interestRateModel_ The address of the interest rate model @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 @param name_ ERC-20 name of this token @param symbol_ ERC-20 symbol of this token @param decimals_ ERC-20 decimal precision of this token @param admin Address of the administrator of this token/
) public initializer { super.initialize( comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, true, admin ); isCEther = true; }
9,559,951
[ 1, 7249, 279, 394, 29538, 1136, 15601, 13667, 225, 532, 337, 1539, 67, 1021, 1758, 434, 326, 1286, 337, 1539, 225, 16513, 4727, 1488, 67, 1021, 1758, 434, 326, 16513, 4993, 938, 225, 2172, 11688, 4727, 49, 970, 21269, 67, 1021, 2172, 7829, 4993, 16, 12304, 635, 404, 73, 2643, 225, 508, 67, 4232, 39, 17, 3462, 508, 434, 333, 1147, 225, 3273, 67, 4232, 39, 17, 3462, 3273, 434, 333, 1147, 225, 15105, 67, 4232, 39, 17, 3462, 6970, 6039, 434, 333, 1147, 225, 3981, 5267, 434, 326, 22330, 434, 333, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 262, 1071, 12562, 288, 203, 565, 2240, 18, 11160, 12, 203, 1377, 532, 337, 1539, 67, 16, 203, 1377, 16513, 4727, 1488, 67, 16, 203, 1377, 2172, 11688, 4727, 49, 970, 21269, 67, 16, 203, 1377, 508, 67, 16, 203, 1377, 3273, 67, 16, 203, 1377, 15105, 67, 16, 203, 1377, 638, 16, 203, 1377, 3981, 203, 565, 11272, 203, 203, 565, 353, 1441, 1136, 273, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xA53de764935d71968c7B5d311E6E76Ba22109a11/sources/DharmaTradeReserveV17ImplementationStaging.sol
Trade tokens for Ether using reserves. Retain the lesser of either max fee or bought amount less quoted amount.
function tradeTokenForEtherUsingReservesSpecifyingFee( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 maximumEtherFeeAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherBought) { totalEtherBought = _tradeTokenForEther( token, tokenAmountFromReserves, tokenAmountFromReserves, quotedEtherAmount, deadline ); uint256 retainedEtherAmount = maximumEtherFeeAmount.min( totalEtherBought.sub(quotedEtherAmount) ); _fireTradeEvent( true, false, address(token), tokenAmountFromReserves, totalEtherBought.sub(retainedEtherAmount), retainedEtherAmount ); }
9,400,950
[ 1, 22583, 2430, 364, 512, 1136, 1450, 400, 264, 3324, 18, 17100, 530, 326, 5242, 264, 434, 3344, 943, 14036, 578, 800, 9540, 3844, 5242, 9298, 3844, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 18542, 1345, 1290, 41, 1136, 7736, 607, 264, 3324, 19302, 310, 14667, 12, 203, 565, 4232, 39, 3462, 1358, 1147, 16, 203, 565, 2254, 5034, 1147, 6275, 1265, 607, 264, 3324, 16, 203, 565, 2254, 5034, 9298, 41, 1136, 6275, 16, 203, 565, 2254, 5034, 4207, 41, 1136, 14667, 6275, 16, 203, 565, 2254, 5034, 14096, 203, 225, 262, 3903, 1338, 5541, 1162, 12, 2996, 18, 862, 2123, 3412, 67, 4349, 5483, 13, 1135, 261, 11890, 5034, 2078, 41, 1136, 13809, 9540, 13, 288, 203, 565, 2078, 41, 1136, 13809, 9540, 273, 389, 20077, 1345, 1290, 41, 1136, 12, 203, 1377, 1147, 16, 203, 1377, 1147, 6275, 1265, 607, 264, 3324, 16, 203, 1377, 1147, 6275, 1265, 607, 264, 3324, 16, 203, 1377, 9298, 41, 1136, 6275, 16, 203, 1377, 14096, 203, 565, 11272, 203, 203, 565, 2254, 5034, 25227, 41, 1136, 6275, 273, 4207, 41, 1136, 14667, 6275, 18, 1154, 12, 203, 1377, 2078, 41, 1136, 13809, 9540, 18, 1717, 12, 15179, 41, 1136, 6275, 13, 203, 565, 11272, 203, 203, 565, 389, 12179, 22583, 1133, 12, 203, 1377, 638, 16, 203, 1377, 629, 16, 203, 1377, 1758, 12, 2316, 3631, 203, 1377, 1147, 6275, 1265, 607, 264, 3324, 16, 203, 1377, 2078, 41, 1136, 13809, 9540, 18, 1717, 12, 1349, 8707, 41, 1136, 6275, 3631, 203, 1377, 25227, 41, 1136, 6275, 203, 565, 11272, 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 ]
./partial_match/1/0x7e321AF42c7e4C9DEa7E6FFC14862cBee1980C29/sources/contracts/core/NibblVaultFactory.sol
@notice unpauses the system @dev can only be called by PAUSER_ROLE
function unPause() external onlyRole(PAUSER_ROLE) override { _unpause(); }
2,877,449
[ 1, 318, 8774, 6117, 326, 2619, 225, 848, 1338, 506, 2566, 635, 15662, 4714, 67, 16256, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 640, 19205, 1435, 3903, 1338, 2996, 12, 4066, 4714, 67, 16256, 13, 3849, 288, 203, 3639, 389, 318, 19476, 5621, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.4.24; // pragma experimental ABIEncoderV2; import "./List.sol"; import "./Util.sol"; contract SimpleExchange is Recoverable { using ExchangeHelper for ExchangeHelper.t; ExchangeHelper.t infoOp; constructor() public { infoOp.init(); } function link(TokenVault vault) external onlyMaster { MiscOp.requireEx(vault != address(0)); infoOp.vault = vault; } /////////////////////////////////////////////////////////////////////////// function () // depositWei external payable { address user = msg.sender; uint256 weis = msg.value; infoOp.depositWei(user, weis); } function withdrawWei(uint256 weis) external { address user = msg.sender; MiscOp.requireEx(user != 0x0); MiscOp.requireEx(weis != 0x0); infoOp.withdrawWei(user, weis); } function balanceOfWei(address user) external view returns(uint256) { MiscOp.requireEx(user != 0x0); return infoOp.balanceOfWei(user); } function findWeiTransactionList(address _user) external view returns(uint256[] transactionType, uint256[] weis, uint256[] createTime) { return infoOp.findWeiTransactionList(_user); } /////////////////////////////////////////////////////////////////////////// function depositToken(address token, uint256 tokenAmount) external { address user = msg.sender; MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); MiscOp.requireEx(tokenAmount != 0x0); infoOp.depositToken(token, user, tokenAmount); } function withdrawToken(address token, uint256 tokenAmount) external { address user = msg.sender; MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); MiscOp.requireEx(tokenAmount != 0x0); infoOp.withdrawToken(token, user, tokenAmount); } function balanceOfToken(address token, address user) external view returns(uint256) { MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); return infoOp.balanceOfToken(token, user); } function findTokenTransactionList(address token, address user) external view returns(uint256[] transactionType, uint256[] tokenAmount, uint256[] createTime) { return infoOp.findTokenTransactionList(token, user); } /////////////////////////////////////////////////////////////////////////// function sell(address token, uint256 tokenAmount, uint256 weis) external returns(uint256) { address user = msg.sender; MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); MiscOp.requireEx(weis != 0x0); MiscOp.requireEx(tokenAmount != 0x0); return infoOp.sell(token, user, tokenAmount, weis); } function buy(address token, uint256 tokenAmount, uint256 weis) external returns(uint256) { address user = msg.sender; MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); MiscOp.requireEx(tokenAmount != 0x0); MiscOp.requireEx(weis != 0x0); return infoOp.buy(token, user, tokenAmount, weis); } function cancelOrder(uint256 orderId) external { address user = msg.sender; MiscOp.requireEx(user != 0x0); infoOp.cancelOrder(user, orderId); } function orderList(address _token) external view returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { return infoOp.orderList(_token); } // function info() // external // view // returns(uint256 key, uint256 value, uint256[1] key2, uint256[1] value2) // { // mlist_keyvalue.keyvalue memory r = infoOp.info(); // return (r.key, r.value, [r.key], [r.value]); // } enum How {a,b,cc,dd} function myOrderList() external pure returns ( // uint256[] id, // address[] token, // address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, uint256[1] tokenAmount, How[1] tokenAmountLeft ) { tokenAmount[0] = 5; tokenAmountLeft[0] = How.dd; } function myxOrderList() external view returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { address _user = msg.sender; MiscOp.requireEx(_user != 0x0); return infoOp.myOrderList(_user); } // order detail, account detail, wei detail // // function orderDetail(uint256 orderId) // status, transactions // // external // // view // // { // // infoOp.orderDetail(orderId); // // } } library ExchangeHelper { using SafeMath for uint256; using mlist_address for mlist_address.t; using mlist_uint256 for mlist_uint256.t; using list_address for list_address.t; using list_uint256 for list_uint256.t; using one_many_address_uint256 for one_many_address_uint256.t; using one_many_uint256_uint256 for one_many_uint256_uint256.t; uint256 constant kOrderSell = 1; uint256 constant kOrderBuy = 2; uint256 constant kTransaction_weiWithdrawal = 111; uint256 constant kTransaction_weiDeposit = 112; uint256 constant kTransaction_weiToOrder = 121; uint256 constant kTransaction_weiFromOrder = 122; uint256 constant kTransaction_tokenWithdrawal = 211; uint256 constant kTransaction_tokenDeposit = 212; uint256 constant kTransaction_tokenToOrder = 221; uint256 constant kTransaction_tokenFromOrder = 222; uint256 constant kTransaction_orderMatch = 300; struct WeiAccountEntry { uint256 weis; } struct WeiAccountInfo { uint256 total; mapping(address => WeiAccountEntry) table; /* key is accountId */ } struct TokenAccountEntry { uint256 tokenAmount; } struct TokenAccountInfo { mapping(address => mapping(address => uint256)) token_user_accountId; mapping(uint256 => TokenAccountEntry) table; /* key is accountId */ one_many_address_uint256.t tokenDic; /* token <-> accountId */ one_many_address_uint256.t userDic; /* user <-> accountId */ } struct ExTokenInfo { mapping(address => mapping(uint256 => uint256)) token_tokenId_exTokenId; one_many_address_uint256.t tokenDic; /* token <-> exTokenId[] */ one_many_uint256_uint256.t tokenIdDic; /* tokenId <-> exTokenId[] */ } struct ERC721TokenAccountInfo { ExTokenInfo exToken; one_many_address_uint256.t userDic; /* owner <-> exTokenId[] */ } struct ERC1203TokenAccountInfo { // multi-class fungible token ExTokenInfo exToken; mapping(uint256 => mapping(address => uint256)) exTokenId_user_accountId; mapping(uint256 => TokenAccountEntry) table; /* key is accountId */ one_many_uint256_uint256.t exTokenIdDic; /* exTokenId <-> accountId */ one_many_uint256_uint256.t userDic; /* user <-> accountId */ } struct FullOrderEntry { uint256 id; address token; address user; uint256 orderType; // 11 for sell, 11 for sellClosed, 21 for buy, 22 for buyClosed uint256 weis; uint256 weisLeft; uint256 tokenAmount; uint256 tokenAmountLeft; // uint256 createTime; } struct BuyOrderEntry { uint256 tokenAmount; // // uint256 price; // in wei uint256 weis; // in wei weis = tokenAmount * price uint256 weisLeft; // uint256 cancelled_tokenAmount; // uint256 filled_tokenAmount; // uint256 filled_weis; // OrderStatus status; uint256 createTime; uint256 closeTime; } struct SellOrderEntry { // uint256 price; // in wei uint256 tokenAmount; // in token unit e.g. tnano uint256 tokenAmountLeft; uint256 weis; // // uint256 cancelled_tokenAmount; // uint256 filled_tokenAmount; // uint256 filled_weis; // OrderStatus status; uint256 createTime; uint256 closeTime; } struct ERC20PartOrderInfo { one_many_address_uint256.t tokenDic; /* token <-> orderId */ one_many_address_uint256.t userDic; /* user <-> orderId */ } struct ERC721PartOrderInfo { one_many_address_uint256.t tokenDic; /* token <-> orderId */ one_many_uint256_uint256.t exTokenDic; /* exTokenId <-> orderId */ one_many_address_uint256.t userDic; /* user <-> orderId */ } struct ERC1203PartOrderInfo { one_many_address_uint256.t tokenDic; /* token <-> orderId */ one_many_uint256_uint256.t exTokenDic; /* exTokenId <-> orderId */ one_many_address_uint256.t userDic; /* user <-> orderId */ } struct OrderInfo { mapping(uint256 => BuyOrderEntry) buyTable; /* key is orderId */ ERC20PartOrderInfo buy; ERC20PartOrderInfo buyClosed; mapping(uint256 => SellOrderEntry) sellTable; /* key is orderId */ ERC20PartOrderInfo sell; ERC20PartOrderInfo sellClosed; } // toOrder, fromOrder, deposit, withdrawal struct WeiTransactionEntry { uint256 transactionType; uint256 weis; uint256 createTime; } struct WeiTransactionInfo { mapping(uint256 => WeiTransactionEntry) transactions; one_many_address_uint256.t userDic; /* key is user address */ one_many_uint256_uint256.t orderDic; /* key is orderId */ } struct FullWeiTransactionEntry { uint256 id; address user; uint256 orderId; uint256 transactionType; uint256 weis; uint256 createTime; } struct TokenTransactionEntry { uint256 transactionType; uint256 tokenAmount; uint256 createTime; } struct TokenTransactionInfo { mapping(uint256 => TokenTransactionEntry) transactions; one_many_address_uint256.t tokenDic; /* key is token address */ one_many_address_uint256.t userDic; /* key is user address */ one_many_uint256_uint256.t orderDic; /* key is orderId */ one_many_uint256_uint256.t accountDic; /* key is orderId */ } struct FullTokenTransactionEntry { uint256 id; address token; address user; uint256 orderId; uint256 transactionType; uint256 tokenAmount; uint256 createTime; } struct OrderTransactionEntry { uint256 tokenAmount; // uint256 price; // in wei uint256 weis; uint256 createTime; } struct OrderTransactionInfo { mapping(uint256 => OrderTransactionEntry) transactions; one_many_address_uint256.t tokenDic; /* key is token address */ one_many_address_uint256.t userBuyDic; /* key is user address */ one_many_address_uint256.t userSellDic; /* key is user address */ one_many_uint256_uint256.t orderBuyDic; /* key is orderId */ one_many_uint256_uint256.t orderSellDic; /* key is orderId */ } struct FullOrderTransactionEntry { uint256 id; address token; address userSell; address userBuy; uint256 orderIdSell; uint256 orderIdBuy; uint256 transactionType; uint256 weis; // uint256 price; // in wei uint256 tokenAmount; uint256 createTime; } struct t { uint256 nextId; // always > 0 list_address.t tokenAmount; /* key is token address */ list_address.t users; /* key is user address */ WeiAccountInfo weis; TokenAccountInfo accounts; OrderInfo orders; OrderTransactionInfo transactions; WeiTransactionInfo transactions_wei; TokenTransactionInfo transactions_token; TokenVault vault; } /////////////////////////////////////////////////////////////////////////// function findWeiTransactionList(t storage _this, address user) internal view returns(uint256[] transactionType, uint256[] weis, uint256[] createTime) { FullWeiTransactionEntry[] memory ls = _findWeiTransactionList(_this, user); transactionType = new uint256[]( ls.length); weis = new uint256[]( ls.length); createTime = new uint256[]( ls.length); for (uint256 i = 0; i < ls.length; i++) { transactionType[i] = ls[i].transactionType; weis[i] = ls[i].weis; createTime[i] = ls[i].createTime; } } function _findWeiTransactionList(t storage _this, address user) private view returns(FullWeiTransactionEntry[] memory) { FullWeiTransactionEntry[] memory mls = new FullWeiTransactionEntry[](19); WeiTransactionInfo storage oi = _this.transactions_wei; list_uint256.t storage ls = oi.userDic.listAt(user); for (uint256 i = 0; i < ls.size(); i++) { uint256 transactionId = ls.at(i); WeiTransactionEntry storage e = oi.transactions[transactionId]; mls[i] = FullWeiTransactionEntry({ id : transactionId, user : user, orderId : 0, transactionType : e.transactionType, weis : e.weis, createTime : e.createTime}); } return mls; } function findTokenTransactionList(t storage _this, address token, address user) internal view returns(uint256[] transactionType, uint256[] tokenAmount, uint256[] createTime) { FullTokenTransactionEntry[] memory ls = _findTokenTransactionList(_this, token, user); transactionType = new uint256[]( ls.length); tokenAmount = new uint256[]( ls.length); createTime = new uint256[]( ls.length); for (uint256 i = 0; i < ls.length; i++) { transactionType[i] = ls[i].transactionType; tokenAmount[i] = ls[i].tokenAmount; createTime[i] = ls[i].createTime; } } function _findTokenTransactionList(t storage _this, address token, address user) private view returns(FullTokenTransactionEntry[] memory) { uint256 accountId = _this.accounts.token_user_accountId[token][user]; return findTokenTransactionListByAccount(_this, accountId); } function findTokenTransactionListByAccount(t storage _this, uint256 accountId) private view returns(FullTokenTransactionEntry[] memory) { FullTokenTransactionEntry[] memory mls = new FullTokenTransactionEntry[](19); TokenTransactionInfo storage oi = _this.transactions_token; list_uint256.t storage ls = oi.accountDic.listAt(accountId); for (uint256 i = 0; i < ls.size(); i++) { uint256 transactionId = ls.at(i); TokenTransactionEntry storage e = oi.transactions[transactionId]; mls[i] = FullTokenTransactionEntry({ id : transactionId, token : oi.tokenDic.oneAt(transactionId), user : oi.userDic.oneAt(transactionId), orderId : 0, transactionType : e.transactionType, tokenAmount : e.tokenAmount, createTime : e.createTime}); } return mls; } function findOrderTransactionList(t storage _this, uint256 orderIdSell) private view returns(FullOrderTransactionEntry[] memory) { FullOrderTransactionEntry[] memory mls = new FullOrderTransactionEntry[](19); OrderTransactionInfo storage oi = _this.transactions; list_uint256.t storage ls = oi.orderSellDic.listAt(orderIdSell); for (uint256 i = 0; i < ls.size(); i++) { uint256 transactionId = ls.at(i); OrderTransactionEntry storage e = oi.transactions[transactionId]; mls[i] = FullOrderTransactionEntry({ id : transactionId, token : oi.tokenDic.oneAt(transactionId), userSell : oi.userSellDic.oneAt(transactionId), userBuy : oi.userBuyDic.oneAt(transactionId), orderIdSell : oi.orderSellDic.oneAt(transactionId), orderIdBuy : oi.orderBuyDic.oneAt(transactionId), transactionType : kTransaction_orderMatch, tokenAmount : e.tokenAmount, // price : e.price, weis : e.weis, createTime : e.createTime}); } return mls; } /////////////////////////////////////////////////////////////////////////// function depositToken(t storage _this, address token, address user, uint256 tokenAmount) internal { mintTokens(_this, token, user, tokenAmount); makeTokenTransaction(_this, token, user, tokenAmount, kTransaction_tokenDeposit); VaultOp.transferERC20From(ERC20(token), user, address(_this.vault), tokenAmount); // VaultOp.transferERC20From(ERC20(token), user, address(this), tokenAmount); } function withdrawToken(t storage _this, address token, address user, uint256 tokenAmount) internal { burnTokens(_this, token, user, tokenAmount); makeTokenTransaction(_this, token, user, tokenAmount, kTransaction_tokenWithdrawal); _this.vault.transferERC20Basic(ERC20Basic(token), user, tokenAmount); // VaultOp.transferERC20Basic(ERC20(token), user, tokenAmount); } function balanceOfToken(t storage _this, address token, address user) internal view returns(uint256) { uint256 accountId = _this.accounts.token_user_accountId[token][user]; TokenAccountEntry storage ae = _this.accounts.table[accountId]; return ae.tokenAmount; } function depositWei(t storage _this, address user, uint256 weis) internal { mintWeis(_this, user, weis); makeWeiTransaction(_this, user, weis, kTransaction_weiDeposit); VaultOp.transferWei(address(_this.vault), weis); // // VaultOp.transferWei(address(this), weis); // nothing } function withdrawWei(t storage _this, address user, uint256 weis) internal { burnWeis(_this, user, weis); makeWeiTransaction(_this, user, weis, kTransaction_weiWithdrawal); _this.vault.transferWei(user, weis); // VaultOp.transferWei(user, weis); } function balanceOfWei(t storage _this, address user) internal view returns(uint256) { return _this.weis.table[user].weis; } function cancelOrder(t storage _this, address user, uint256 orderId) internal { closeUserOrder(_this, user, orderId); } function orderList(t storage _this, address _token) internal view returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { FullOrderEntry[] memory ls = findBuyOrders_t(_this, _token); return flat(ls); } // function info(t storage _this) // internal // view // returns(mlist_keyvalue.keyvalue memory) // { // mlist_keyvalue.keyvalue memory r; // return r; // } function myOrderList(t storage _this, address _user) internal view returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { FullOrderEntry[] memory ls = findBuyOrders_u(_this, _user); return flat(ls); } function flat(FullOrderEntry[] memory ls) private pure returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { id = new uint256[]( ls.length); token = new address[]( ls.length); user = new address[]( ls.length); // orderType = new uint256[]( ls.length); // weis = new uint256[]( ls.length); // weisLeft = new uint256[]( ls.length); // tokenAmount = new uint256[]( ls.length); tokenAmountLeft = new uint256[]( ls.length); for(uint256 i = 0; i < ls.length; i++){ id[i] = ls[i].id; token[i] = ls[i].token; user[i] = ls[i].user; // orderType[i] = ls[i].orderType; // weis[i] = ls[i].weis; // weisLeft[i] = ls[i].weisLeft; // tokenAmount[i] = ls[i].tokenAmount; tokenAmountLeft[i] = ls[i].tokenAmountLeft; } } // function orderDetail(t storage _this, uint256 orderId) // status, transactions // internal // view // { // } function init(t storage _this) internal { _this.nextId = 1; // always > 0 } function buy(t storage _this, address token, address user, uint256 tokenAmount, uint256 weis) internal returns(uint256) { uint256 buyOrderId = buyLimitPrice(_this, token, user, tokenAmount, weis); OrderInfo storage oi = _this.orders; BuyOrderEntry storage oe = oi.buyTable[buyOrderId]; mlist_uint256.t memory ls = findSellOrders(_this, token, tokenAmount, weis); for (uint256 i = 0; i < ls.size(); i++) { if (oe.weis <= 0) { break; } uint256 sellOrderId = ls.at(i); matchOrders(_this, sellOrderId, buyOrderId); } return buyOrderId; } function sell(t storage _this, address token, address user, uint256 tokenAmount, uint256 weis) internal returns(uint256) { uint256 sellOrderId = sellLimitPrice(_this, token, user, tokenAmount, weis); OrderInfo storage oi = _this.orders; SellOrderEntry storage oe = oi.sellTable[buyOrderId]; mlist_uint256.t memory ls = findBuyOrders(_this, token, tokenAmount, weis); for (uint256 i = 0; i < ls.size(); i++) { if (oe.tokenAmount <= 0) { break; } uint256 buyOrderId = ls.at(i); matchOrders(_this, sellOrderId, buyOrderId); } return sellOrderId; } /////////////////////////////////////////////////////////////////////////// function nextId(t storage _this) private returns(uint256) { return _this.nextId++; } function mintWeis(t storage _this, address user, uint256 weis2) private { WeiAccountEntry storage we = _this.weis.table[user]; we.weis = we.weis.add(weis2); _this.weis.total = _this.weis.total.add(weis2); } function mintTokens(t storage _this, address token, address user, uint256 tokenAmount2) private { uint256 accountId = safeAddTokenAccount(_this, token, user); TokenAccountEntry storage ae = _this.accounts.table[accountId]; ae.tokenAmount = ae.tokenAmount.add(tokenAmount2); } function burnWeis(t storage _this, address user, uint256 weis2) private { WeiAccountEntry storage we = _this.weis.table[user]; we.weis = we.weis.sub(weis2); _this.weis.total = _this.weis.total.sub(weis2); } function burnTokens(t storage _this, address token, address user, uint256 tokenAmount2) private { uint256 accountId = safeAddTokenAccount(_this, token, user); TokenAccountEntry storage ae = _this.accounts.table[accountId]; ae.tokenAmount = ae.tokenAmount.sub(tokenAmount2); } function moveCloseOrder(ERC20PartOrderInfo storage oi, ERC20PartOrderInfo storage oiClosed, uint256 orderId) private { address token = oi.tokenDic.oneAt(orderId); address user = oi.userDic.oneAt(orderId); oi.tokenDic.remove(token, orderId); oiClosed.tokenDic.add(token, orderId); oi.userDic.remove(user, orderId); oiClosed.userDic.add(user, orderId); } function safeAddTokenAccount(t storage _this, address token, address user) private returns(uint256) { uint256 accountId = _this.accounts.token_user_accountId[token][user]; if (accountId == 0) { accountId = nextId(_this); _this.tokenAmount.safeAdd(token); _this.users.safeAdd(user); _this.accounts.tokenDic.add(token, accountId); _this.accounts.userDic.add(user, accountId); _this.accounts.table[accountId] = TokenAccountEntry({ tokenAmount: 0 }); _this.accounts.token_user_accountId[token][user] = accountId; } return accountId; } function findBuyOrders(t storage _this, address token, uint256 tokenAmount, uint256 weis) private view returns(mlist_uint256.t memory) { mlist_uint256.t memory mls; OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.buy.tokenDic.listAt(token); for (uint256 i = 0; i < ls.size(); i++) { uint256 oId = ls.at(i); BuyOrderEntry storage oe = oi.buyTable[oId]; if (oe.weis * tokenAmount >= weis * oe.tokenAmount) { mls.add(oId); } } return mls; } function findSellOrders(t storage _this, address token, uint256 tokenAmount, uint256 weis) private view returns(mlist_uint256.t memory) { mlist_uint256.t memory mls; mls.clear(); // MiscOp.requireEx(mls.size() == 0); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.sell.tokenDic.listAt(token); // MiscOp.requireEx(ls.size() == 1); for (uint256 i = 0; i < ls.size(); i++) { uint256 oId = ls.at(i); SellOrderEntry storage oe = oi.sellTable[oId]; if (oe.weis * tokenAmount <= weis * oe.tokenAmount) { mls.add(oId); } } return mls; } function findBuyOrders_t(t storage _this, address token) private view returns(FullOrderEntry[] memory) { FullOrderEntry[] memory mls = new FullOrderEntry[](19); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.buy.tokenDic.listAt(token); for (uint256 i = 0; i < ls.size(); i++) { uint256 orderId = ls.at(i); BuyOrderEntry storage e = oi.buyTable[orderId]; mls[i] = FullOrderEntry({ id : orderId, token : oi.sell.tokenDic.oneAt(orderId), user : oi.sell.userDic.oneAt(orderId), orderType : kOrderBuy, weis : e.weis, weisLeft : e.weisLeft, tokenAmount : 0, tokenAmountLeft : 0}); } return mls; } function findSellOrders_t(t storage _this, address token) private view returns(FullOrderEntry[] memory) { FullOrderEntry[] memory mls = new FullOrderEntry[](19); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.sell.tokenDic.listAt(token); for (uint256 i = 0; i < ls.size(); i++) { uint256 orderId = ls.at(i); SellOrderEntry storage e = oi.sellTable[orderId]; mls[i] = FullOrderEntry({ id : orderId, token : oi.sell.tokenDic.oneAt(orderId), user : oi.sell.userDic.oneAt(orderId), orderType : kOrderSell, weis : 0, weisLeft : 0, tokenAmount : e.tokenAmount, tokenAmountLeft : e.tokenAmountLeft}); } return mls; } function findBuyOrders_u(t storage _this, address user) private view returns(FullOrderEntry[] memory) { FullOrderEntry[] memory mls = new FullOrderEntry[](19); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.buy.userDic.listAt(user); for (uint256 i = 0; i < ls.size(); i++) { uint256 orderId = ls.at(i); BuyOrderEntry storage e = oi.buyTable[orderId]; mls[i] = FullOrderEntry({ id : orderId, token : oi.sell.tokenDic.oneAt(orderId), user : oi.sell.userDic.oneAt(orderId), orderType : kOrderBuy, weis : e.weis, weisLeft : e.weisLeft, tokenAmount : 0, tokenAmountLeft : 0}); } return mls; } function findSellOrders_u(t storage _this, address user) private view returns(FullOrderEntry[] memory) { FullOrderEntry[] memory mls = new FullOrderEntry[](19); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.sell.userDic.listAt(user); for (uint256 i = 0; i < ls.size(); i++) { uint256 orderId = ls.at(i); SellOrderEntry storage e = oi.sellTable[orderId]; mls[i] = FullOrderEntry({ id : orderId, token : oi.sell.tokenDic.oneAt(orderId), user : oi.sell.userDic.oneAt(orderId), orderType : kOrderSell, weis : 0, weisLeft : 0, tokenAmount : e.tokenAmount, tokenAmountLeft : e.tokenAmountLeft}); } return mls; } // solium-disable-next-line indentation function createOrderIndex(ERC20PartOrderInfo storage oi, address token, address user, uint256 orderId) private { oi.tokenDic.add(token, orderId); oi.userDic.add(user, orderId); } // solium-disable-next-line indentation function createOrderTransactionIndex(t storage _this, address token, address userSell, address userBuy, uint256 orderIdSell, uint256 orderIdBuy, uint256 transactionId) private { _this.transactions.tokenDic.add(token, transactionId); _this.transactions.userSellDic.add(userSell, transactionId); _this.transactions.orderSellDic.add(orderIdSell, transactionId); _this.transactions.userBuyDic.add(userBuy, transactionId); _this.transactions.orderBuyDic.add(orderIdBuy, transactionId); } function createTokenTransactionIndex(t storage _this, address token, address user, uint256 orderId, uint256 transactionId) private { _this.transactions_token.tokenDic.add(token, transactionId); _this.transactions_token.userDic.add(user, transactionId); _this.transactions_token.orderDic.add(orderId, transactionId); } function createWeiTransactionIndex(t storage _this, address user, uint256 orderId, uint256 transactionId) private { _this.transactions_wei.userDic.add(user, transactionId); _this.transactions_wei.orderDic.add(orderId, transactionId); } function buyLimitPrice(t storage _this, address token, address user, uint256 tokenAmount, uint256 weis) private returns(uint256) { MiscOp.requireEx(tokenAmount != 0); MiscOp.requireEx(weis != 0); safeAddTokenAccount(_this, token, user); uint256 orderId = nextId(_this); burnWeis(_this, user, weis); uint256 transactionId = makeWeiTransaction(_this, user, weis, kTransaction_weiToOrder); createWeiTransactionIndex(_this, user, orderId, transactionId); uint256 ts = MiscOp.currentTime(); _this.orders.buyTable[orderId] = BuyOrderEntry({ // price: price, tokenAmount: tokenAmount, weis: weis, weisLeft: weis, createTime: ts, closeTime: 0 }); createOrderIndex(_this.orders.buy, token, user, orderId); return orderId; } function sellLimitPrice(t storage _this, address token, address user, uint256 tokenAmount, uint256 weis) private returns(uint256) { MiscOp.requireEx(tokenAmount != 0); MiscOp.requireEx(weis != 0); safeAddTokenAccount(_this, token, user); uint256 orderId = nextId(_this); burnTokens(_this, token, user, tokenAmount); uint256 transactionId = makeTokenTransaction(_this, token, user, tokenAmount, kTransaction_tokenToOrder); createTokenTransactionIndex(_this, token, user, orderId, transactionId); uint256 ts = MiscOp.currentTime(); _this.orders.sellTable[orderId] = SellOrderEntry({ // price: price, tokenAmount: tokenAmount, weis: weis, tokenAmountLeft: tokenAmount, createTime: ts, closeTime: 0 }); createOrderIndex(_this.orders.sell, token, user, orderId); return orderId; } function closeUserOrder(t storage _this, address user, uint256 orderId) private { bool b = _this.orders.sell.userDic.exists(user, orderId); if (b) { closeSellOrder(_this, orderId); } b = _this.orders.buy.userDic.exists(user, orderId); if (b) { closeBuyOrder(_this, orderId); } } function closeOrder(t storage _this, uint256 orderId) private { address token = _this.orders.sell.tokenDic.oneAt(orderId); if (token != 0x0) { closeSellOrder(_this, orderId); } token = _this.orders.buy.tokenDic.oneAt(orderId); if (token != 0x0) { closeBuyOrder(_this, orderId); } } function closeSellOrder(t storage _this, uint256 sellOrderId) private { address token = _this.orders.sell.tokenDic.oneAt(sellOrderId); address seller = _this.orders.sell.userDic.oneAt(sellOrderId); SellOrderEntry storage oeSell = _this.orders.sellTable[sellOrderId]; uint256 tokenAmount = oeSell.tokenAmountLeft; if (tokenAmount > 0) { oeSell.tokenAmountLeft = 0; mintTokens(_this, token, seller, tokenAmount); makeTokenTransaction(_this, token, seller, tokenAmount, kTransaction_tokenFromOrder); } if (oeSell.closeTime == 0) { moveCloseOrder(_this.orders.sell, _this.orders.sellClosed, sellOrderId); uint256 ts = MiscOp.currentTime(); oeSell.closeTime = ts; } } function closeBuyOrder(t storage _this, uint256 buyOrderId) private { address buyer = _this.orders.buy.userDic.oneAt(buyOrderId); BuyOrderEntry storage oeBuy = _this.orders.buyTable[buyOrderId]; uint256 weis = oeBuy.weisLeft; if (weis > 0) { oeBuy.weisLeft = 0; mintWeis(_this, buyer, weis); makeWeiTransaction(_this, buyer, weis, kTransaction_weiFromOrder); } if (oeBuy.closeTime == 0) { moveCloseOrder(_this.orders.buy, _this.orders.buyClosed, buyOrderId); uint256 ts = MiscOp.currentTime(); oeBuy.closeTime = ts; } } function matchOrders(t storage _this, uint256 sellOrderId, uint256 buyOrderId) private { uint256 transactionId = matchOrders_1(_this, sellOrderId, buyOrderId); matchOrders_2(_this, sellOrderId, buyOrderId, transactionId); matchOrders_3(_this, sellOrderId, buyOrderId); } function matchOrders_1(t storage _this, uint256 sellOrderId, uint256 buyOrderId) private returns(uint256 transactionId) { address token = _this.orders.sell.tokenDic.oneAt(sellOrderId); address tokenB = _this.orders.buy.tokenDic.oneAt(buyOrderId); MiscOp.requireEx(token == tokenB); SellOrderEntry storage oeSell = _this.orders.sellTable[sellOrderId]; BuyOrderEntry storage oeBuy = _this.orders.buyTable[buyOrderId]; MiscOp.requireEx(oeSell.weis * oeBuy.tokenAmount <= oeBuy.weis * oeSell.tokenAmount); // maximize deal uint256 tokenAmount2 = oeSell.tokenAmountLeft; uint256 weis2 = oeBuy.weisLeft; if (oeBuy.weisLeft < oeSell.tokenAmountLeft * oeSell.weis / oeSell.tokenAmount) { weis2 = oeBuy.weisLeft; tokenAmount2 = (weis2 * oeBuy.tokenAmount / oeBuy.weis + weis2 * oeSell.tokenAmount / oeSell.weis) / 2; } else if (oeSell.tokenAmountLeft < oeBuy.weisLeft * oeBuy.tokenAmount / oeBuy.weis) { tokenAmount2 = oeSell.tokenAmountLeft; weis2 = (tokenAmount2 * oeSell.weis / oeSell.tokenAmount + tokenAmount2 * oeBuy.weis / oeBuy.tokenAmount) / 2; } else { weis2 = (oeBuy.weisLeft + oeSell.tokenAmountLeft * oeSell.weis / oeSell.tokenAmount) / 2; tokenAmount2 = (oeSell.tokenAmountLeft + oeBuy.weisLeft * oeBuy.tokenAmount / oeBuy.weis) / 2; } if (tokenAmount2 > 0) { // solium-disable-next-line indentation transactionId = makeTransaction(_this, // price, tokenAmount2, weis2); address seller = _this.orders.sell.userDic.oneAt(sellOrderId); address buyer = _this.orders.buy.userDic.oneAt(buyOrderId); oeSell.tokenAmountLeft = oeSell.tokenAmountLeft.sub(tokenAmount2); oeBuy.weisLeft = oeBuy.weisLeft.sub(weis2); mintWeis(_this, seller, weis2); mintTokens(_this, token, buyer, tokenAmount2); } return transactionId; } function matchOrders_2(t storage _this, uint256 sellOrderId, uint256 buyOrderId, uint256 transactionId) private { if (transactionId > 0) { address token = _this.orders.sell.tokenDic.oneAt(sellOrderId); address seller = _this.orders.sell.userDic.oneAt(sellOrderId); address buyer = _this.orders.buy.userDic.oneAt(buyOrderId); // solium-disable-next-line indentation createOrderTransactionIndex(_this, token, seller, buyer, sellOrderId, buyOrderId, transactionId); } } function matchOrders_3(t storage _this, uint256 sellOrderId, uint256 buyOrderId) private { SellOrderEntry storage oeSell = _this.orders.sellTable[sellOrderId]; BuyOrderEntry storage oeBuy = _this.orders.buyTable[buyOrderId]; if (oeBuy.weisLeft < oeBuy.weis / oeBuy.tokenAmount) { closeBuyOrder(_this, buyOrderId); } if (oeSell.tokenAmountLeft < oeSell.tokenAmount / oeSell.weis) { closeSellOrder(_this, sellOrderId); } } // solium-disable-next-line indentation function makeTransaction(t storage _this, // address token, address seller, address buyer, // uint256 sellOrderId, uint256 buyOrderId, // uint256 tokenAmount, uint256 weis) private returns(uint256 transactionId) { transactionId = nextId(_this); uint256 ts = MiscOp.currentTime(); _this.transactions.transactions[transactionId] = OrderTransactionEntry({ // price: price, tokenAmount: tokenAmount, weis: weis, createTime: ts }); return transactionId; } // solium-disable-next-line indentation function makeWeiTransaction(t storage _this, address user, uint256 weis, uint256 _type) private returns(uint256 transactionId) { transactionId = nextId(_this); _this.transactions_wei.userDic.add(user, transactionId); uint256 ts = MiscOp.currentTime(); _this.transactions_wei.transactions[transactionId] = WeiTransactionEntry({ transactionType: _type, weis: weis, createTime: ts }); return transactionId; } // solium-disable-next-line indentation function makeTokenTransaction(t storage _this, address token, address user, uint256 tokenAmount, uint256 _type) private returns(uint256 transactionId) { transactionId = nextId(_this); uint256 accountId = safeAddTokenAccount(_this, token, user); _this.transactions_token.tokenDic.add(token, transactionId); _this.transactions_token.userDic.add(user, transactionId); _this.transactions_token.accountDic.add(accountId, transactionId); uint256 ts = MiscOp.currentTime(); _this.transactions_token.transactions[transactionId] = TokenTransactionEntry({ transactionType: _type, tokenAmount: tokenAmount, createTime: ts }); return transactionId; } }
uint256[] orderType, uint256[] weis, uint256[] weisLeft, uint256[] tokenAmount,
function myxOrderList() external view returns ( uint256[] id, address[] token, address[] user, uint256[] tokenAmountLeft ) { address _user = msg.sender; MiscOp.requireEx(_user != 0x0); return infoOp.myOrderList(_user); }
12,734,764
[ 1, 11890, 5034, 8526, 1353, 559, 16, 2254, 5034, 8526, 732, 291, 16, 2254, 5034, 8526, 732, 291, 3910, 16, 2254, 5034, 8526, 1147, 6275, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 3399, 92, 2448, 682, 1435, 203, 202, 9375, 203, 202, 1945, 203, 202, 6154, 261, 203, 202, 202, 11890, 5034, 8526, 612, 16, 203, 202, 202, 2867, 8526, 1147, 16, 203, 202, 202, 2867, 8526, 729, 16, 203, 202, 202, 11890, 5034, 8526, 1147, 6275, 3910, 203, 202, 13, 7010, 202, 95, 203, 202, 202, 2867, 389, 1355, 273, 1234, 18, 15330, 31, 203, 202, 202, 11729, 71, 3817, 18, 6528, 424, 24899, 1355, 480, 374, 92, 20, 1769, 203, 202, 202, 2463, 1123, 3817, 18, 4811, 2448, 682, 24899, 1355, 1769, 203, 202, 97, 203, 7010, 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 ]
./full_match/1/0x9D0EA4afc828E202714434ccc950F1911F4B084E/sources/browser/WebaverseAccount.sol
0x08E242bB06D85073e69222aF8273af419d19E4f6, "lol"
contract WebaverseAccount { event MetadataSet( address owner, string key, string value ); mapping (address => mapping(string => string)) private addressToMetadata; pragma solidity ^0.6.0; constructor() public {} function getMetadata(address owner, string memory key) public view returns (string memory) { return addressToMetadata[owner][key]; } function setMetadata(address owner, string memory key, string memory value) public { require(msg.sender == owner); addressToMetadata[owner][key] = value; emit MetadataSet(owner, key, value); } }
17,141,742
[ 1, 20, 92, 6840, 41, 3247, 22, 70, 38, 7677, 40, 28, 3361, 9036, 73, 8148, 28855, 69, 42, 28, 5324, 23, 1727, 24, 3657, 72, 3657, 41, 24, 74, 26, 16, 315, 80, 355, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 2999, 69, 2476, 3032, 288, 203, 565, 871, 6912, 694, 12, 203, 1377, 1758, 3410, 16, 203, 1377, 533, 498, 16, 203, 1377, 533, 460, 203, 565, 11272, 203, 203, 565, 2874, 261, 2867, 516, 2874, 12, 1080, 516, 533, 3719, 3238, 1758, 774, 2277, 31, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 565, 3885, 1435, 1071, 2618, 203, 565, 445, 11159, 12, 2867, 3410, 16, 533, 3778, 498, 13, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 1758, 774, 2277, 63, 8443, 6362, 856, 15533, 203, 565, 289, 203, 377, 203, 565, 445, 444, 2277, 12, 2867, 3410, 16, 533, 3778, 498, 16, 533, 3778, 460, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 1758, 774, 2277, 63, 8443, 6362, 856, 65, 273, 460, 31, 203, 540, 203, 3639, 3626, 6912, 694, 12, 8443, 16, 498, 16, 460, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x7805A1169B8a5C040d3107356A2bF29de8A3b0Bc/sources/contracts/europeanrouletteWAVE.sol
standard wager-transfer part
function playHighLowWAVE(string memory _HighLowBet, uint _betamount) external whenNotPaused noBlacklistedPlayers returns (uint256) { require( minimumBetAmountWaveTokens < _betamount, "below minimum bet size!" ); require( WaveToken.balanceOf(msg.sender) >= _betamount, "not enough Tokens!" ); require( WaveToken.balanceOf(address(this)) >= _betamount * 36, "bank cant cover this bet at the moment, come back later!" ); require( WaveToken.allowance(msg.sender, address(this)) >= _betamount, "increase allowance!" ); require( WaveToken.transferFrom(msg.sender, address(this), _betamount), "Transfer failed!" ); uint256 requestId_Bet = requestRandomWords(); BetsPlaced[requestId_Bet].requestID = requestId_Bet; BetsPlaced[requestId_Bet].amount = _betamount; BetsPlaced[requestId_Bet].BetType = "HighLowBet"; BetsPlaced[requestId_Bet].valueString = _HighLowBet; BetsPlaced[requestId_Bet].valueInt; BetsPlaced[requestId_Bet].payoutRatio = 2; BetsPlaced[requestId_Bet].player = payable(msg.sender); emit BetRequest(BetsPlaced[requestId_Bet].requestID, msg.sender); return requestId_Bet; }
7,180,721
[ 1, 10005, 341, 6817, 17, 13866, 1087, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6599, 8573, 10520, 59, 26714, 12, 1080, 3778, 389, 8573, 10520, 38, 278, 16, 2254, 389, 70, 278, 8949, 13, 203, 3639, 3903, 203, 3639, 1347, 1248, 28590, 203, 3639, 1158, 13155, 18647, 1749, 3907, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 5224, 38, 278, 6275, 22368, 5157, 411, 389, 70, 278, 8949, 16, 203, 5411, 315, 27916, 5224, 2701, 963, 4442, 203, 3639, 11272, 203, 540, 203, 3639, 2583, 12, 203, 5411, 24314, 1345, 18, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 389, 70, 278, 8949, 16, 203, 5411, 315, 902, 7304, 13899, 4442, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 24314, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 389, 70, 278, 8949, 380, 6580, 16, 203, 5411, 315, 10546, 848, 88, 5590, 333, 2701, 622, 326, 10382, 16, 12404, 1473, 5137, 4442, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 24314, 1345, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3719, 1545, 389, 70, 278, 8949, 16, 203, 5411, 315, 267, 11908, 1699, 1359, 4442, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 24314, 1345, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 70, 278, 8949, 3631, 203, 5411, 315, 5912, 2535, 4442, 203, 3639, 11272, 203, 3639, 2254, 5034, 14459, 67, 38, 278, 273, 590, 8529, 7363, 5621, 203, 3639, 605, 2413, 6029, 72, 63, 2293, 548, 67, 38, 278, 8009, 2293, 734, 273, 2 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20CappedUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function __ERC20Capped_init(uint256 cap_) internal initializer { __Context_init_unchained(); __ERC20Capped_init_unchained(cap_); } function __ERC20Capped_init_unchained(uint256 cap_) internal initializer { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_mint}. */ function _mint(address account, uint256 amount) internal virtual override { require( ERC20Upgradeable.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded" ); super._mint(account, amount); } uint256[50] private __gap; } // File: contracts/Liti/liti.sol pragma solidity >=0.8.0; contract LitiCapital is ERC20CappedUpgradeable, OwnableUpgradeable, PausableUpgradeable { struct tokenRecoverInfo { uint256 lockExpires; address newAddress; } mapping(address => bool) private isApproved; mapping(address => bool) private isFrozen; mapping(address => tokenRecoverInfo) private tokenRecoverRecords; event Freeze(address account, bytes32 data); event Unfreeze(address account, bytes32 data); event UserApproved(address account, bytes32 data); event TokenRecoverRequested( address currentAddress, address newAddress, bytes32 data ); function initialize() public initializer { __ERC20_init("LitiCapital", "LITI"); __ERC20Capped_init(12000000); __Ownable_init(); __Pausable_init(); require(approveUser(hex"00", msg.sender)); } /** * @dev return the value of decimals as 0. */ function decimals() public view virtual override returns (uint8) { return 0; } /** * @dev return true if {account} is paused. */ function freezeStatus(address account) public view returns (bool) { return isFrozen[account]; } /** * @dev return true if {account} is approved. */ function approvalStatus(address account) public view returns (bool) { return isApproved[account]; } /** * @dev Set an {account} as approved. * {data} represent encrypted information about the user approved * * Emits {UserApproved} event */ function approveUser(bytes32 data, address account) public onlyOwner returns (bool) { require(!isApproved[account], "The account has already been approved"); isApproved[account] = true; emit UserApproved(account, data); return true; } /** * @dev Unfreeze {account}. * {data} represent encrypted information about the reasons for unfreezing. * * Emits {Unfreeze} event */ function unfreeze(bytes32 data, address account) public onlyOwner returns (bool) { require(isFrozen[account], "The account is not frozen"); isFrozen[account] = false; emit Unfreeze(account, data); return true; } /** * @dev Freeze {account}. * {data} represent encrypted information about the reasons for freezing. * * Emits {Freeze} event */ function freeze(bytes32 data, address account) public onlyOwner returns (bool) { require(!isFrozen[account], "The account has been already frozen"); isFrozen[account] = true; emit Freeze(account, data); return true; } /** * @dev Pause contract. */ function PauseContract() public onlyOwner returns (bool) { require(!paused(), "Contract is already paused"); _pause(); return true; } /** * @dev Resume contract. */ function UnpauseContract() public onlyOwner returns (bool) { require(paused(), "Contract is not paused"); _unpause(); return true; } /** * @dev Issues an {amount} new shares to {recipient}. */ function issue(address recipient, uint256 amount) public onlyOwner returns (bool) { _mint(recipient, amount); return true; } /** * @dev Checks before transfering tokens {from} and {to} are not: * paused, unApproved. Also checks if the contract is not paused * * Requirements: * {to} is approved * {to} is not paused * {from} is not paused * Contract is not paused */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { require(isApproved[to], "Transfer to unapproved user"); require(!isFrozen[to], "Transfer to paused user"); require(!isFrozen[from], "Transfer from paused user"); require(!paused(), "Contract paused"); } /** * @dev In case of lost access to wallet it can be used to start a * procedure to reasign tokens from {currentAddress} a to {newAddress}. * after a period of 30 days has passed. * * Emits a {TokenRecoverRequested} Event * */ function tokenRecoveryRequest( address currentAccount, address newAccount, bytes32 data ) public onlyOwner returns (bool) { uint256 lockExpires = block.timestamp + (30) * 1 days; tokenRecoverRecords[currentAccount] = tokenRecoverInfo( lockExpires, newAccount ); isFrozen[currentAccount] = true; emit TokenRecoverRequested(currentAccount, newAccount, data); return true; } /** * @dev Allows token reasignament after lock period expires * * Emits a {Transfer} Event * * Requirements: * Current timestamp is larger than the {lockExpires} * records */ function recoverTokens(address from) public onlyOwner returns (bool) { tokenRecoverInfo memory info = tokenRecoverRecords[from]; require( info.lockExpires <= block.timestamp, "Atempted token recovery before lock period expiration" ); _transfer(from, info.newAddress, balanceOf(from)); tokenRecoverRecords[from] = tokenRecoverInfo(0, address(0)); return true; } /** * @dev Allows burning tokens in the {owner()} account */ function burn() public onlyOwner returns (bool) { _burn(owner(), balanceOf(owner())); return true; } }
* @dev Unfreeze {account}. {data} represent encrypted information about the reasons for unfreezing. Emits {Unfreeze} event/
function unfreeze(bytes32 data, address account) public onlyOwner returns (bool) { require(isFrozen[account], "The account is not frozen"); isFrozen[account] = false; emit Unfreeze(account, data); return true; }
12,072,460
[ 1, 984, 29631, 288, 4631, 5496, 288, 892, 97, 2406, 6901, 1779, 2973, 326, 14000, 364, 640, 9156, 94, 310, 18, 7377, 1282, 288, 984, 29631, 97, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 445, 640, 29631, 12, 3890, 1578, 501, 16, 1758, 2236, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 291, 42, 9808, 63, 4631, 6487, 315, 1986, 2236, 353, 486, 12810, 8863, 203, 3639, 17646, 9808, 63, 4631, 65, 273, 629, 31, 203, 3639, 3626, 1351, 29631, 12, 4631, 16, 501, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
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. { } }
these params arent used in the mock, but this is to maintain compatibility with balancer API
contract BalancerMock is Balancer { uint256 price = 0; function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual override view returns (uint256 spotPrice) { return price; } function setPrice(uint256 newPrice) external { price = newPrice; } }
7,359,619
[ 1, 451, 3392, 859, 279, 547, 1399, 316, 326, 5416, 16, 1496, 333, 353, 358, 17505, 8926, 598, 14887, 1491, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 5191, 9865, 353, 605, 5191, 288, 203, 203, 565, 2254, 5034, 6205, 273, 374, 31, 203, 203, 203, 203, 203, 565, 445, 1322, 13130, 5147, 55, 634, 14667, 12, 2867, 1147, 382, 16, 1758, 1147, 1182, 13, 203, 203, 3639, 3903, 203, 203, 3639, 5024, 203, 203, 3639, 3849, 203, 203, 3639, 1476, 203, 203, 3639, 1135, 261, 11890, 5034, 16463, 5147, 13, 203, 203, 565, 288, 203, 203, 3639, 327, 6205, 31, 203, 203, 565, 289, 203, 203, 203, 203, 203, 565, 445, 444, 5147, 12, 11890, 5034, 394, 5147, 13, 3903, 288, 203, 203, 3639, 6205, 273, 394, 5147, 31, 203, 203, 565, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title -FoMo-3D v0.7.1 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ .--,-``-. *========,---,.======================____==========================/ / '.=======,---,====* * ,' .' | ,' , `. / ../ ; .' .' `\ * ,---.' | ,---. ,-+-,.' _ | ,---. \ ``\ .`- ' ,---.' \ * | | .' ' ,'\ ,-+-. ; , || ' ,'\ ,---,. \___\/ \ : | | .`\ | * : : : / / | ,--.'|' | || / / | ,' .' | \ : | : : | ' | * : | |-, . ; ,. : | | ,', | |, . ; ,. : ,---.' | / / / | ' ' ; : * | : ;/| ' | |: : | | / | |--' ' | |: : | | .' \ \ \ ' | ; . | * | | .' ' | .; : | : | | , ' | .; : : |.' ___ / : | | | : | ' * ' : ' | : | | : | |/ | : | `---' / /\ / : ' : | / ; * | | | \ \ / | | |`-' \ \ / / ,,/ ',- . | | '` ,/ * | : \ `----' | ;/ `----' \ ''\ ; ; : .' *====| | ,'=============='---'==========(long version)===========\ \ .'===| ,.'======* * `----' `--`-,,-' '---' * ╔═╗┌─┐┌─┐┬┌─┐┬┌─┐┬ ┌─────────────────────────┐ ╦ ╦┌─┐┌┐ ╔═╗┬┌┬┐┌─┐ * ║ ║├┤ ├┤ ││ │├─┤│ │ https://exitscam.me │ ║║║├┤ ├┴┐╚═╗│ │ ├┤ * ╚═╝└ └ ┴└─┘┴┴ ┴┴─┘ └─┬─────────────────────┬─┘ ╚╩╝└─┘└─┘╚═╝┴ ┴ └─┘ * ┌────────────────────────────────┘ └──────────────────────────────┐ * │╔═╗┌─┐┬ ┬┌┬┐┬┌┬┐┬ ┬ ╔╦╗┌─┐┌─┐┬┌─┐┌┐┌ ╦┌┐┌┌┬┐┌─┐┬─┐┌─┐┌─┐┌─┐┌─┐ ╔═╗┌┬┐┌─┐┌─┐┬┌─│ * │╚═╗│ ││ │ │││ │ └┬┘ ═ ║║├┤ └─┐││ ┬│││ ═ ║│││ │ ├┤ ├┬┘├┤ ├─┤│ ├┤ ═ ╚═╗ │ ├─┤│ ├┴┐│ * │╚═╝└─┘┴─┘┴─┴┘┴ ┴ ┴ ═╩╝└─┘└─┘┴└─┘┘└┘ ╩┘└┘ ┴ └─┘┴└─└ ┴ ┴└─┘└─┘ ╚═╝ ┴ ┴ ┴└─┘┴ ┴│ * │ ┌──────────┐ ┌───────┐ ┌─────────┐ ┌────────┐ │ * └────┤ Inventor ├───────────┤ Justo ├────────────┤ Sumpunk ├──────────────┤ Mantso ├──┘ * └──────────┘ └───────┘ └─────────┘ └────────┘ * ┌─────────────────────────────────────────────────────────┐ ╔╦╗┬ ┬┌─┐┌┐┌┬┌─┌─┐ ╔╦╗┌─┐ * │ ChungkueiBlock, Ambius, Aritz Cracker, Cryptoknight, │ ║ ├─┤├─┤│││├┴┐└─┐ ║ │ │ * │ Capex, JogFera, The Shocker, Daok, Randazzz, PumpRabbi, │ ╩ ┴ ┴┴ ┴┘└┘┴ ┴└─┘ ╩ └─┘ * │ Kadaz, Incognito Jo, Lil Stronghands, Ninja Turtle, └───────────────────────────┐ * │ Psaints, Satoshi, Vitalik, Nano 2nd, Bogdanoffs Isaac Newton, Nikola Tesla, │ * │ Le Comte De Saint Germain, Albert Einstein, Socrates, & all the volunteer moderator │ * │ & support staff, content, creators, autonomous agents, and indie devs for P3D. │ * │ Without your help, we wouldn't have the time to code this. │ * └─────────────────────────────────────────────────────────────────────────────────────┘ * * This product is protected under license. Any unauthorized copy, modification, or use without * express written consent from the creators is prohibited. * * WARNING: THIS PRODUCT IS HIGHLY ADDICTIVE. IF YOU HAVE AN ADDICTIVE NATURE. DO NOT PLAY. */ //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents { } contract FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; // otherFoMo3D private otherF3D_; address private otherF3D_; // remove the 害虫 // DiviesInterface constant private Divies = DiviesInterface(0xe7d5f7a1afbfeb44894c1114fb021cab7e0367fd); // 简化社区分红 // JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0x548e2295fc38b69000ff43a730933919b08c2562); PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x4c9382454cb0553aee069d302c3ef2e48b0d7852); // hack 闭源合约 // F3DexternalSettingsInterface constant private extSettings = F3DexternalSettingsInterface(0x85C2d5079DC6C2856116C41f4EDd2E3EBBb63B5C); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "imfomo Long Official"; string constant public symbol = "imfomo"; uint256 private rndExtra_ = 30; // length of the very first ICO uint256 private rndGap_ = 30; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 10 minutes; // round timer starts at this uint256 constant private rndInc_ = 60 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 10 minutes; // max length a round timer can be address constant private reward = 0x0e4AF6199f2b92d6677c44d7722CB60cD46FCef6; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(31,0); //50% to pot, 15% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(38,0); //43% to pot, 15% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(61,0); //20% to pot, 15% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(46,0); //35% to pot, 15% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15,0); //58% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(15,0); //58% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(30,0); //58% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30,0); //58% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(58)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter // 当一轮刚开始时,合约收到的总ETH数小于100且某用户累计充值超过1ETH的时候,将不再能买到keys,你多余钱会直接计入你的收益 // if (round_[_rID].eth < 1000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) // { // uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); // uint256 _refund = _eth.sub(_availableLimit); // plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); // _eth = _availableLimit; // } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; // >= 10 ether if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; // >= 1 && < 10 ether } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; // >= 0.1 && <= 1 ether } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(58)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards // if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) // { // // This ensures Team Just cannot influence the outcome of FoMo3D with // // bank migrations by breaking outgoing transactions. // // Something we would never do. But that's not the point. // // We spent 2000$ in eth re-deploying just to patch this, we hold the // // highest belief that everything we create should be trustless. // // Team JUST, The name you shouldn't have to trust. // _p3d = _p3d.add(_com); // _com = 0; // } _p3d = _p3d.add(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies // Divies.deposit.value(_p3d)(); if (_p3d > 0) reward.send(_p3d); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; uint256 _p3d; // if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) // { // // This ensures Team Just cannot influence the outcome of FoMo3D with // // bank migrations by breaking outgoing transactions. // // Something we would never do. But that's not the point. // // We spent 2000$ in eth re-deploying just to patch this, we hold the // // highest belief that everything we create should be trustless. // // Team JUST, The name you shouldn't have to trust. // _p3d = _com; // _com = 0; // } _p3d = _p3d.add(_com); // pay 1% out to FoMo3D short uint256 _long = _eth / 100; otherF3D_.send(_long); // distribute share to affiliate uint256 _aff; uint256 _aff2; uint256 _affID2 = plyr_[_affID].laff; if (_affID2 != 0 && plyr_[_affID2].name != "") { _aff = _eth.mul(10) / 100; _aff2 = _eth.mul(5) / 100; plyr_[_affID2].aff = _aff2.add(plyr_[_affID2].aff); } else { _aff = _eth.mul(15) / 100; } // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != "") { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); // emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _p3d.add(_aff); } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract // Divies.deposit.value(_p3d)(); reward.send(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(19)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f || msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f || msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f, "only team just can activate" ); // make sure that its been linked. require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } function setOtherFomo(address _otherF3D) public { // only team just can activate require( msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f || msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f || msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f, "only team just can activate" ); // make sure that it HASNT yet been linked. require(address(otherF3D_) == address(0), "silly dev, you already did that"); // set up other fomo3d (fast or long) for pot swap // otherF3D_ = otherFoMo3D(_otherF3D); otherF3D_ = _otherF3D; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface otherFoMo3D { function potSwap() external payable; } interface F3DexternalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } interface DiviesInterface { function deposit() external payable; } interface JIincForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
round timer starts at this
uint256 constant private rndInit_ = 10 minutes;
1,181,014
[ 1, 2260, 5441, 2542, 622, 333, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 5381, 3238, 20391, 2570, 67, 273, 1728, 6824, 31, 1171, 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 ]
./partial_match/1/0x358bB001F953cB9284a29B17C68bc66a5B3B0f0E/sources/FROGGY.sol
Solidity only automatically asserts when dividing by 0 assert(a == b * c + a % b); There is no case in which this doesn't hold
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; }
2,597,510
[ 1, 25044, 560, 1338, 6635, 26124, 1347, 3739, 10415, 635, 374, 1815, 12, 69, 422, 324, 225, 276, 397, 279, 738, 324, 1769, 225, 6149, 353, 1158, 648, 316, 1492, 333, 3302, 1404, 6887, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 16, 533, 3778, 9324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 203, 203, 565, 2583, 12, 70, 405, 374, 16, 9324, 1769, 203, 203, 565, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 203, 203, 7010, 203, 565, 327, 276, 31, 203, 203, 225, 289, 203, 203, 7010, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IStandardERC20} from '../../base/interfaces/IStandardERC20.sol'; import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol'; import { ISynthereumPoolOnChainPriceFeed } from './interfaces/IPoolOnChainPriceFeed.sol'; import { ISynthereumPoolOnChainPriceFeedStorage } from './interfaces/IPoolOnChainPriceFeedStorage.sol'; import {ISynthereumFinder} from '../../core/interfaces/IFinder.sol'; import {ISynthereumDeployer} from '../../core/interfaces/IDeployer.sol'; import {SynthereumInterfaces} from '../../core/Constants.sol'; import {Strings} from '@openzeppelin/contracts/utils/Strings.sol'; import { EnumerableSet } from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; import { FixedPoint } from '@uma/core/contracts/common/implementation/FixedPoint.sol'; import {SynthereumPoolOnChainPriceFeedLib} from './PoolOnChainPriceFeedLib.sol'; import {Lockable} from '@uma/core/contracts/common/implementation/Lockable.sol'; import { AccessControlEnumerable } from '@openzeppelin/contracts/access/AccessControlEnumerable.sol'; /** * @title Token Issuer Contract * @notice Collects collateral and issues synthetic assets */ contract SynthereumPoolOnChainPriceFeed is AccessControlEnumerable, ISynthereumPoolOnChainPriceFeedStorage, ISynthereumPoolOnChainPriceFeed, Lockable { using FixedPoint for FixedPoint.Unsigned; using SynthereumPoolOnChainPriceFeedLib for Storage; using EnumerableSet for EnumerableSet.AddressSet; //---------------------------------------- // Constants //---------------------------------------- bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer'); bytes32 public constant LIQUIDITY_PROVIDER_ROLE = keccak256('Liquidity Provider'); //---------------------------------------- // Storage //---------------------------------------- Storage private poolStorage; //---------------------------------------- // Events //---------------------------------------- event Mint( address indexed account, address indexed pool, uint256 collateralSent, uint256 numTokensReceived, uint256 feePaid, address recipient ); event Redeem( address indexed account, address indexed pool, uint256 numTokensSent, uint256 collateralReceived, uint256 feePaid, address recipient ); event Exchange( address indexed account, address indexed sourcePool, address indexed destPool, uint256 numTokensSent, uint256 destNumTokensReceived, uint256 feePaid, address recipient ); event Settlement( address indexed account, address indexed pool, uint256 numTokens, uint256 collateralSettled ); event SetFeePercentage(uint256 feePercentage); event SetFeeRecipients(address[] feeRecipients, uint32[] feeProportions); // We may omit the pool from event since we can recover it from the address of smart contract emitting event, but for query convenience we include it in the event event AddDerivative(address indexed pool, address indexed derivative); event RemoveDerivative(address indexed pool, address indexed derivative); //---------------------------------------- // Modifiers //---------------------------------------- modifier onlyMaintainer() { require( hasRole(MAINTAINER_ROLE, msg.sender), 'Sender must be the maintainer' ); _; } modifier onlyLiquidityProvider() { require( hasRole(LIQUIDITY_PROVIDER_ROLE, msg.sender), 'Sender must be the liquidity provider' ); _; } //---------------------------------------- // Constructor //---------------------------------------- /** * @notice The derivative's collateral currency must be an ERC20 * @notice The validator will generally be an address owned by the LP * @notice `_startingCollateralization should be greater than the expected asset price multiplied * by the collateral requirement. The degree to which it is greater should be based on * the expected asset volatility. * @param _derivative The perpetual derivative * @param _finder The Synthereum finder * @param _version Synthereum version * @param _roles The addresses of admin, maintainer, liquidity provider and validator * @param _startingCollateralization Collateralization ratio to use before a global one is set * @param _fee The fee structure */ constructor( IDerivative _derivative, ISynthereumFinder _finder, uint8 _version, Roles memory _roles, uint256 _startingCollateralization, Fee memory _fee ) nonReentrant { _setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(LIQUIDITY_PROVIDER_ROLE, DEFAULT_ADMIN_ROLE); _setupRole(DEFAULT_ADMIN_ROLE, _roles.admin); _setupRole(MAINTAINER_ROLE, _roles.maintainer); _setupRole(LIQUIDITY_PROVIDER_ROLE, _roles.liquidityProvider); poolStorage.initialize( _version, _finder, _derivative, FixedPoint.Unsigned(_startingCollateralization) ); poolStorage.setFeePercentage(_fee.feePercentage); poolStorage.setFeeRecipients(_fee.feeRecipients, _fee.feeProportions); } //---------------------------------------- // External functions //---------------------------------------- /** * @notice Add a derivate to be controlled by this pool * @param derivative A perpetual derivative */ function addDerivative(IDerivative derivative) external override onlyMaintainer nonReentrant { poolStorage.addDerivative(derivative); } /** * @notice Remove a derivative controlled by this pool * @param derivative A perpetual derivative */ function removeDerivative(IDerivative derivative) external override onlyMaintainer nonReentrant { poolStorage.removeDerivative(derivative); } /** * @notice Mint synthetic tokens using fixed amount of collateral * @notice This calculate the price using on chain price feed * @notice User must approve collateral transfer for the mint request to succeed * @param mintParams Input parameters for minting (see MintParams struct) * @return syntheticTokensMinted Amount of synthetic tokens minted by a user * @return feePaid Amount of collateral paid by the minter as fee */ function mint(MintParams memory mintParams) external override nonReentrant returns (uint256 syntheticTokensMinted, uint256 feePaid) { (syntheticTokensMinted, feePaid) = poolStorage.mint(mintParams); } /** * @notice Redeem amount of collateral using fixed number of synthetic token * @notice This calculate the price using on chain price feed * @notice User must approve synthetic token transfer for the redeem request to succeed * @param redeemParams Input parameters for redeeming (see RedeemParams struct) * @return collateralRedeemed Amount of collateral redeeem by user * @return feePaid Amount of collateral paid by user as fee */ function redeem(RedeemParams memory redeemParams) external override nonReentrant returns (uint256 collateralRedeemed, uint256 feePaid) { (collateralRedeemed, feePaid) = poolStorage.redeem(redeemParams); } /** * @notice Exchange a fixed amount of synthetic token of this pool, with an amount of synthetic tokens of an another pool * @notice This calculate the price using on chain price feed * @notice User must approve synthetic token transfer for the redeem request to succeed * @param exchangeParams Input parameters for exchanging (see ExchangeParams struct) * @return destNumTokensMinted Amount of collateral redeeem by user * @return feePaid Amount of collateral paid by user as fee */ function exchange(ExchangeParams memory exchangeParams) external override nonReentrant returns (uint256 destNumTokensMinted, uint256 feePaid) { (destNumTokensMinted, feePaid) = poolStorage.exchange(exchangeParams); } /** * @notice Called by a source Pool's `exchange` function to mint destination tokens * @notice This functon can be called only by a pool registred in the PoolRegister contract * @param srcDerivative Derivative used by the source pool * @param derivative The derivative of the destination pool to use for mint * @param collateralAmount The amount of collateral to use from the source Pool * @param numTokens The number of new tokens to mint */ function exchangeMint( IDerivative srcDerivative, IDerivative derivative, uint256 collateralAmount, uint256 numTokens ) external override nonReentrant { poolStorage.exchangeMint( srcDerivative, derivative, FixedPoint.Unsigned(collateralAmount), FixedPoint.Unsigned(numTokens) ); } /** * @notice Liquidity provider withdraw collateral from the pool * @param collateralAmount The amount of collateral to withdraw */ function withdrawFromPool(uint256 collateralAmount) external override onlyLiquidityProvider nonReentrant { poolStorage.withdrawFromPool(FixedPoint.Unsigned(collateralAmount)); } /** * @notice Move collateral from Pool to its derivative in order to increase GCR * @param derivative Derivative on which to deposit collateral * @param collateralAmount The amount of collateral to move into derivative */ function depositIntoDerivative( IDerivative derivative, uint256 collateralAmount ) external override onlyLiquidityProvider nonReentrant { poolStorage.depositIntoDerivative( derivative, FixedPoint.Unsigned(collateralAmount) ); } /** * @notice Start a slow withdrawal request * @notice Collateral can be withdrawn once the liveness period has elapsed * @param derivative Derivative from which the collateral withdrawal is requested * @param collateralAmount The amount of excess collateral to withdraw */ function slowWithdrawRequest(IDerivative derivative, uint256 collateralAmount) external override onlyLiquidityProvider nonReentrant { poolStorage.slowWithdrawRequest( derivative, FixedPoint.Unsigned(collateralAmount) ); } /** * @notice Withdraw collateral after a withdraw request has passed it's liveness period * @param derivative Derivative from which collateral withdrawal was requested * @return amountWithdrawn Amount of collateral withdrawn by slow withdrawal */ function slowWithdrawPassedRequest(IDerivative derivative) external override onlyLiquidityProvider nonReentrant returns (uint256 amountWithdrawn) { amountWithdrawn = poolStorage.slowWithdrawPassedRequest(derivative); } /** * @notice Withdraw collateral immediately if the remaining collateral is above GCR * @param derivative Derivative from which fast withdrawal was requested * @param collateralAmount The amount of excess collateral to withdraw * @return amountWithdrawn Amount of collateral withdrawn by fast withdrawal */ function fastWithdraw(IDerivative derivative, uint256 collateralAmount) external override onlyLiquidityProvider nonReentrant returns (uint256 amountWithdrawn) { amountWithdrawn = poolStorage.fastWithdraw( derivative, FixedPoint.Unsigned(collateralAmount) ); } /** * @notice Redeem tokens after derivative emergency shutdown * @param derivative Derivative for which settlement is requested * @return amountSettled Amount of collateral withdrawn after emergency shutdown */ function settleEmergencyShutdown(IDerivative derivative) external override nonReentrant returns (uint256 amountSettled) { amountSettled = poolStorage.settleEmergencyShutdown( derivative, LIQUIDITY_PROVIDER_ROLE ); } /** * @notice Update the fee percentage * @param _feePercentage The new fee percentage */ function setFeePercentage(uint256 _feePercentage) external override onlyMaintainer nonReentrant { poolStorage.setFeePercentage(FixedPoint.Unsigned(_feePercentage)); } /** * @notice Update the addresses of recipients for generated fees and proportions of fees each address will receive * @param _feeRecipients An array of the addresses of recipients that will receive generated fees * @param _feeProportions An array of the proportions of fees generated each recipient will receive */ function setFeeRecipients( address[] calldata _feeRecipients, uint32[] calldata _feeProportions ) external override onlyMaintainer nonReentrant { poolStorage.setFeeRecipients(_feeRecipients, _feeProportions); } /** * @notice Reset the starting collateral ratio - for example when you add a new derivative without collateral * @param startingCollateralRatio Initial ratio between collateral amount and synth tokens */ function setStartingCollateralization(uint256 startingCollateralRatio) external override onlyMaintainer nonReentrant { poolStorage.setStartingCollateralization( FixedPoint.Unsigned(startingCollateralRatio) ); } //---------------------------------------- // External view functions //---------------------------------------- /** * @notice Get Synthereum finder of the pool * @return finder Returns finder contract */ function synthereumFinder() external view override returns (ISynthereumFinder finder) { finder = poolStorage.finder; } /** * @notice Get Synthereum version * @return poolVersion Returns the version of the Synthereum pool */ function version() external view override returns (uint8 poolVersion) { poolVersion = poolStorage.version; } /** * @notice Get the collateral token * @return collateralCurrency The ERC20 collateral token */ function collateralToken() external view override returns (IERC20 collateralCurrency) { collateralCurrency = poolStorage.collateralToken; } /** * @notice Get the synthetic token associated to this pool * @return syntheticCurrency The ERC20 synthetic token */ function syntheticToken() external view override returns (IERC20 syntheticCurrency) { syntheticCurrency = poolStorage.syntheticToken; } /** * @notice Get all the derivatives associated to this pool * @return Return list of all derivatives */ function getAllDerivatives() external view override returns (IDerivative[] memory) { EnumerableSet.AddressSet storage derivativesSet = poolStorage.derivatives; uint256 numberOfDerivatives = derivativesSet.length(); IDerivative[] memory derivatives = new IDerivative[](numberOfDerivatives); for (uint256 j = 0; j < numberOfDerivatives; j++) { derivatives[j] = (IDerivative(derivativesSet.at(j))); } return derivatives; } /** * @notice Check if a derivative is in the withelist of this pool * @param derivative Perpetual derivative * @return isAdmitted Return true if in the withelist otherwise false */ function isDerivativeAdmitted(address derivative) external view override returns (bool isAdmitted) { isAdmitted = poolStorage.derivatives.contains(address(derivative)); } /** * @notice Get the starting collateral ratio of the pool * @return startingCollateralRatio Initial ratio between collateral amount and synth tokens */ function getStartingCollateralization() external view override returns (uint256 startingCollateralRatio) { startingCollateralRatio = poolStorage.startingCollateralization.rawValue; } /** * @notice Get the synthetic token symbol associated to this pool * @return symbol The ERC20 synthetic token symbol */ function syntheticTokenSymbol() external view override returns (string memory symbol) { symbol = IStandardERC20(address(poolStorage.syntheticToken)).symbol(); } /** * @notice Returns infos about fee set * @return fee Percentage and recipients of fee */ function getFeeInfo() external view override returns (Fee memory fee) { fee = poolStorage.fee; } /** * @notice Returns price identifier of the pool * @return identifier Price identifier */ function getPriceFeedIdentifier() external view override returns (bytes32 identifier) { identifier = poolStorage.priceIdentifier; } /** * @notice Calculate the fees a user will have to pay to mint tokens with their collateral * @param collateralAmount Amount of collateral on which fee is calculated * @return fee Amount of fee that must be paid */ function calculateFee(uint256 collateralAmount) external view override returns (uint256 fee) { fee = FixedPoint .Unsigned(collateralAmount) .mul(poolStorage.fee.feePercentage) .rawValue; } //---------------------------------------- // Public functions //---------------------------------------- /** * @notice Update the fee percentage, recipients and recipient proportions * @param _fee Fee struct containing percentage, recipients and proportions */ function setFee(Fee memory _fee) public override onlyMaintainer nonReentrant { poolStorage.setFeePercentage(_fee.feePercentage); poolStorage.setFeeRecipients(_fee.feeRecipients, _fee.feeProportions); } }
* @notice Called by a source Pool's `exchange` function to mint destination tokens @notice This functon can be called only by a pool registred in the PoolRegister contract @param srcDerivative Derivative used by the source pool @param derivative The derivative of the destination pool to use for mint @param collateralAmount The amount of collateral to use from the source Pool @param numTokens The number of new tokens to mint/
function exchangeMint( IDerivative srcDerivative, IDerivative derivative, uint256 collateralAmount, uint256 numTokens ) external override nonReentrant { poolStorage.exchangeMint( srcDerivative, derivative, FixedPoint.Unsigned(collateralAmount), FixedPoint.Unsigned(numTokens) ); }
5,448,876
[ 1, 8185, 635, 279, 1084, 8828, 1807, 1375, 16641, 68, 445, 358, 312, 474, 2929, 2430, 225, 1220, 12882, 265, 848, 506, 2566, 1338, 635, 279, 2845, 960, 376, 1118, 316, 326, 8828, 3996, 6835, 225, 1705, 26239, 1535, 14969, 427, 1535, 1399, 635, 326, 1084, 2845, 225, 16417, 1021, 16417, 434, 326, 2929, 2845, 358, 999, 364, 312, 474, 225, 4508, 2045, 287, 6275, 1021, 3844, 434, 4508, 2045, 287, 358, 999, 628, 326, 1084, 8828, 225, 818, 5157, 1021, 1300, 434, 394, 2430, 358, 312, 474, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 7829, 49, 474, 12, 203, 565, 1599, 264, 427, 1535, 1705, 26239, 1535, 16, 203, 565, 1599, 264, 427, 1535, 16417, 16, 203, 565, 2254, 5034, 4508, 2045, 287, 6275, 16, 203, 565, 2254, 5034, 818, 5157, 203, 225, 262, 3903, 3849, 1661, 426, 8230, 970, 288, 203, 565, 2845, 3245, 18, 16641, 49, 474, 12, 203, 1377, 1705, 26239, 1535, 16, 203, 1377, 16417, 16, 203, 1377, 15038, 2148, 18, 13290, 12, 12910, 2045, 287, 6275, 3631, 203, 1377, 15038, 2148, 18, 13290, 12, 2107, 5157, 13, 203, 565, 11272, 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 ]
// File: contracts/GSN/Context.sol pragma solidity ^0.5.16; /* * @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: contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.16; /** * @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: contracts/math/SafeMath.sol pragma solidity ^0.5.16; /** * @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: contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.16; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.16; /** * @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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { 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() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: contracts/crowdsale/Crowdsale.sol pragma solidity ^0.5.16; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; 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. */ function () 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 nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_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 { 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 { _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 { _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.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: contracts/math/Math.sol pragma solidity ^0.5.16; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/crowdsale/emission/AllowanceCrowdsale.sol pragma solidity ^0.5.16; /** * @title AllowanceCrowdsale * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. */ contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; 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) public { 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 { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } // File: contracts/crowdsale/validation/TimedCrowdsale.sol pragma solidity ^0.5.16; /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * 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) public { // 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() internal view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() internal 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 onlyWhileOpen view { 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; } } // File: contracts/ownership/Ownable.sol pragma solidity ^0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/cores/DateTime.sol pragma solidity ^0.5.16; contract DateTime { /* Date and Time utilities for ethereum contracts */ uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; struct _DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } function isLeapYear(uint16 year) public pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) public pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal pure returns (_DateTime memory dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour dt.hour = getHour(timestamp); // Minute dt.minute = getMinute(timestamp); // Second dt.second = getSecond(timestamp); // Day of week. dt.weekday = getWeekday(timestamp); } function getYear(uint timestamp) public pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint timestamp) public pure returns (uint8) { return uint8(timestamp % 60); } function getWeekday(uint timestamp) public pure returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) { return toTimestamp(year, month, day, 0, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, minute, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public pure returns (uint timestamp) { uint16 i; // Year for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } // Month uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } // Day timestamp += DAY_IN_SECONDS * (day - 1); // Hour timestamp += HOUR_IN_SECONDS * (hour); // Minute timestamp += MINUTE_IN_SECONDS * (minute); // Second timestamp += second; return timestamp; } } // File: contracts/cores/XPLLCrowdsale.sol pragma solidity ^0.5.16; /** * @title XPLLTokenCrowdsale */ contract XPLLCrowdsale is AllowanceCrowdsale, TimedCrowdsale, Ownable { DateTime d = new DateTime(); constructor ( uint256 openingTime, uint256 closingTime, uint256 rate, address payable wallet, address tokenWallet, IERC20 token ) public AllowanceCrowdsale(tokenWallet) Crowdsale(rate, wallet, token) TimedCrowdsale(openingTime, closingTime) {} function getOpeningTime() public view returns (uint16, uint8, uint8, uint8, uint8, uint8) { uint256 timestamp = openingTime(); return (d.getYear(timestamp), d.getMonth(timestamp),d.getDay(timestamp), d.getHour(timestamp), d.getMinute(timestamp), d.getSecond(timestamp)); } function getClosingTime() public view returns (uint16, uint8, uint8, uint8, uint8, uint8) { uint256 timestamp = closingTime(); return (d.getYear(timestamp), d.getMonth(timestamp),d.getDay(timestamp), d.getHour(timestamp), d.getMinute(timestamp), d.getSecond(timestamp)); } function changeClosingTime(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public onlyOwner { uint256 timestamp = d.toTimestamp(year, month, day, hour, minute, second); _extendTime(timestamp); } }
* @return the crowdsale opening time./
function openingTime() internal view returns (uint256) { return _openingTime; }
133,900
[ 1, 2463, 326, 276, 492, 2377, 5349, 10890, 813, 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 ]
[ 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, 10890, 950, 1435, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 3190, 310, 950, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./interfaces/ILiquidityReserve.sol"; import "./liquidity-reserve/factory/LiquidityReserveFactory.sol"; /** * @title AlkemiNetwork * @notice This contract manage Alkemi Network on-chain process */ contract AlkemiNetwork is LiquidityReserveFactory { /// @notice owner address address public owner; /// @notice alkemi oracle address address public alkemiOracle; mapping(address => address[]) public providerReserves; mapping(address => address[]) public tokenReserves; /// @notice settlement id uint256 public currentSettlementId; event ReserveCreate( address indexed reserve, address indexed liquidityProvider, address indexed beneficiary, uint256 lockingPeriod, uint256 lockingPrice, uint8 lockingPricePosition ); constructor() public { _setOwner(msg.sender); currentSettlementId = 1; } /** * @notice Verifies that the caller is the Owner */ modifier onlyOwner() { require( msg.sender == owner, "AlkemiNetwork: Only owner can perform this operation" ); _; } /** * @notice Verifies that the calles is Alkemi Oracle */ modifier onlyAlkemiOracle() { require( msg.sender == alkemiOracle, "AlkemiNetwork: Only Alkemi Oracle can perform this operation" ); _; } /** * @notice Get liquidity reserves addresses of a liquidity provider * @param _liquidityProvider liquidity provider address * @return active liquidity reserve contract addresses */ function providerLiquidityReserves(address _liquidityProvider) public view returns (address[] memory) { address[] memory _reserves = providerReserves[_liquidityProvider]; address[] memory _activeReserves = new address[](_reserves.length); uint256 j = 0; for (uint256 i = 0; i < _reserves.length; i++) { if (ILiquidityReserve(_reserves[i]).isActive()) { _activeReserves[j] = _reserves[i]; j++; } } return _activeReserves; } /** * @notice Get liquidity reserves addresses of a liquidity provider that hold specific asset * @param _liquidityProvider liquidity provider address * @param _asset asset address * @return active liquidity reserve contract addresses */ function providerTokenReserves(address _liquidityProvider, address _asset) public view returns (address[] memory) { address[] memory _reserves = providerReserves[_liquidityProvider]; address[] memory _activeReserves = new address[](_reserves.length); uint256 j = 0; for (uint256 i = 0; i < _reserves.length; i++) { if (ILiquidityReserve(_reserves[i]).isActive() && (ILiquidityReserve(_reserves[i]).asset() == _asset)) { _activeReserves[j] = _reserves[i]; j++; } } return _activeReserves; } /** * @notice Get liquidity reserves addresses that hold a specific asset * @param _asset asset address * @return liquidity reserves addresses */ function tokenLiquidityReserves(address _asset) public view returns (address[] memory) { address[] memory _reserves = tokenReserves[_asset]; address[] memory _activeReserves = new address[](_reserves.length); uint256 j = 0; for (uint256 i = 0; i < _reserves.length; i++) { if (ILiquidityReserve(_reserves[i]).isActive()) { _activeReserves[i] = _reserves[i]; j++; } } return _activeReserves; } /** * @notice Creates and initialises a new LiquidityReserve * @param _beneficiary earnings beneficiary (address(0) if the earnings goes to the current reserve address) * @param _asset asset address * @param _lockingPeriod funds locking period * @param _lockingPrice release funds when hitting this price * @param _lockingPricePosition locking price position * @return Address of new Liquidity Reserve */ function createLiquidityReserve( address _linkToken, address _beneficiary, address _asset, uint256 _createdAt, uint256 _lockingPeriod, uint256 _lockingPrice, uint8 _lockingPricePosition ) public returns (address) { address r = _createLiquidityReserve( _linkToken, msg.sender, address(this), _beneficiary, _asset, _createdAt, _lockingPeriod, _lockingPrice, _lockingPricePosition ); providerReserves[msg.sender].push(r); tokenReserves[_asset].push(r); emit ReserveCreate( r, msg.sender, _beneficiary, _lockingPeriod, _lockingPrice, _lockingPricePosition ); } /** * @notice Set new owner address * @dev can only be called by the AlkemiNetwork owner * @param _owner Address of the new Owner */ function setNewOwner(address _owner) public onlyOwner { _setOwner(_owner); } /** * @notice Set Alkemi Oracle address * @dev can only be called by the AlkemiNetwork owner * @param _oracle oracle address */ function setAlkemiOracle(address _oracle) public onlyOwner { _setAlkemiOracle(_oracle); } function _setOwner(address _owner) internal { require( (_owner != address(0)) && (_owner != address(this)), "AlkemiNetwork: invalid owner address" ); owner = _owner; } function _setAlkemiOracle(address _oracle) internal { require(_oracle != address(0), "AlkemiNetwork: invalid oracle address"); alkemiOracle = _oracle; } }
* @notice Creates and initialises a new LiquidityReserve @param _beneficiary earnings beneficiary (address(0) if the earnings goes to the current reserve address) @param _asset asset address @param _lockingPeriod funds locking period @param _lockingPrice release funds when hitting this price @param _lockingPricePosition locking price position @return Address of new Liquidity Reserve/
function createLiquidityReserve( address _linkToken, address _beneficiary, address _asset, uint256 _createdAt, uint256 _lockingPeriod, uint256 _lockingPrice, uint8 _lockingPricePosition ) public returns (address) { address r = _createLiquidityReserve( _linkToken, msg.sender, address(this), _beneficiary, _asset, _createdAt, _lockingPeriod, _lockingPrice, _lockingPricePosition ); providerReserves[msg.sender].push(r); tokenReserves[_asset].push(r); emit ReserveCreate( r, msg.sender, _beneficiary, _lockingPeriod, _lockingPrice, _lockingPricePosition ); }
15,842,434
[ 1, 2729, 471, 2172, 6141, 279, 394, 511, 18988, 24237, 607, 6527, 225, 389, 70, 4009, 74, 14463, 814, 425, 1303, 899, 27641, 74, 14463, 814, 261, 2867, 12, 20, 13, 309, 326, 425, 1303, 899, 13998, 358, 326, 783, 20501, 1758, 13, 225, 389, 9406, 3310, 1758, 225, 389, 739, 310, 5027, 284, 19156, 18887, 3879, 225, 389, 739, 310, 5147, 3992, 284, 19156, 1347, 6800, 1787, 333, 6205, 225, 389, 739, 310, 5147, 2555, 18887, 6205, 1754, 327, 5267, 434, 394, 511, 18988, 24237, 1124, 6527, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 752, 48, 18988, 24237, 607, 6527, 12, 203, 3639, 1758, 389, 1232, 1345, 16, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 1758, 389, 9406, 16, 203, 3639, 2254, 5034, 389, 4824, 861, 16, 203, 3639, 2254, 5034, 389, 739, 310, 5027, 16, 203, 3639, 2254, 5034, 389, 739, 310, 5147, 16, 203, 3639, 2254, 28, 389, 739, 310, 5147, 2555, 203, 565, 262, 1071, 1135, 261, 2867, 13, 288, 203, 3639, 1758, 436, 273, 389, 2640, 48, 18988, 24237, 607, 6527, 12, 203, 5411, 389, 1232, 1345, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 389, 70, 4009, 74, 14463, 814, 16, 203, 5411, 389, 9406, 16, 203, 5411, 389, 4824, 861, 16, 203, 5411, 389, 739, 310, 5027, 16, 203, 5411, 389, 739, 310, 5147, 16, 203, 5411, 389, 739, 310, 5147, 2555, 203, 3639, 11272, 203, 203, 3639, 2893, 607, 264, 3324, 63, 3576, 18, 15330, 8009, 6206, 12, 86, 1769, 203, 3639, 1147, 607, 264, 3324, 63, 67, 9406, 8009, 6206, 12, 86, 1769, 203, 203, 3639, 3626, 1124, 6527, 1684, 12, 203, 5411, 436, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 389, 70, 4009, 74, 14463, 814, 16, 203, 5411, 389, 739, 310, 5027, 16, 203, 5411, 389, 739, 310, 5147, 16, 203, 5411, 389, 739, 310, 5147, 2555, 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 ]
claimers[0xEB079Ee381FC821B809F6110cCF7a8439C7A6870] = 0; // seq: 0 -> tkn_id: 0 claimers[0xcBD56A71a02fA7AA01bF1c94c0AeB2828Bebdc0A] = 1; // seq: 1 -> tkn_id: 1 claimers[0x9E1fDAB0FE4141fe269060f098bc7076d248cE7B] = 2; // seq: 2 -> tkn_id: 2 claimers[0x33aEA8f43D9685683b236B20a1818aFcD48204cD] = 3; // seq: 3 -> tkn_id: 3 claimers[0xFD289c26cEF8BB89A76252d9F4617cf54ce4EeBD] = 4; // seq: 4 -> tkn_id: 4 claimers[0x04bfcB7b6bc81361F14c1E2C7592d712e3b9f456] = 5; // seq: 5 -> tkn_id: 5 claimers[0x47E51859134f7d7F7379B1AEcD17a19924025A10] = 6; // seq: 6 -> tkn_id: 6 claimers[0x557159300478941E61cb60A46340F8100C590A56] = 7; // seq: 7 -> tkn_id: 7 claimers[0x7Ed273A361D6bb16833f0E563C313e205738112f] = 8; // seq: 8 -> tkn_id: 8 claimers[0x010594cA1B98ffEd9dFE3d15b749f8BaE3F21C1B] = 9; // seq: 9 -> tkn_id: 9 claimers[0x27221550A0ab5487e79460cd80C3E2aFDB48134e] = 10; // seq: 10 -> tkn_id: 10 claimers[0xF3920288e9DCCFED1AE5a05E466d5da2289062FC] = 11; // seq: 11 -> tkn_id: 11 claimers[0x8dca66E74007d8aD89aFC399d131030Ef29311eF] = 12; // seq: 12 -> tkn_id: 12 claimers[0x355B8F6059F5414AB1F69FcA34088c4aDC554B7f] = 13; // seq: 13 -> tkn_id: 13 claimers[0x020BE4338B750B85c73E598bF468E505A8eb76Ea] = 14; // seq: 14 -> tkn_id: 14 claimers[0x04B00a9F997799F4e265D8796a5F2d22C7A8b9AD] = 15; // seq: 15 -> tkn_id: 15 claimers[0xf8ab6312272E4f2eAB48ddcbD00D905e0E1bCb55] = 16; // seq: 16 -> tkn_id: 16 claimers[0x6B745dEfEE931Ee790DFe5333446eF454c45D8Cf] = 17; // seq: 17 -> tkn_id: 17 claimers[0xE770748e5781f171a0364fbd013188Bc0b33E72f] = 18; // seq: 18 -> tkn_id: 18 claimers[0xEa07596132df9F23Af112593dF0C27A0275d67E5] = 19; // seq: 19 -> tkn_id: 19 claimers[0xB22E58d1550D984b580c564E1dE7868521150988] = 20; // seq: 20 -> tkn_id: 20 claimers[0xf6EA8168a1D1D5d36f22436ad2030d397a616619] = 21; // seq: 21 -> tkn_id: 21 claimers[0x424E9cC4c00aD160c3f36b5471514a6C36a8d73e] = 22; // seq: 22 -> tkn_id: 22 claimers[0x365F34a3236c00823C7844885Ac6BF7a15430eD2] = 23; // seq: 23 -> tkn_id: 23 claimers[0x333C5dBa8179822056F2289BdeDe1B53A863F577] = 24; // seq: 24 -> tkn_id: 24 claimers[0xC9de959443935C3f3CC8E82889d5E80e8cD4a8a9] = 25; // seq: 25 -> tkn_id: 25 claimers[0xE2853A8Ba2e42e78cF8a6b063056F067307fB8f4] = 26; // seq: 26 -> tkn_id: 26 claimers[0xE8926AeBb36A046858D882309e7Aea367F8DB6Cd] = 27; // seq: 27 -> tkn_id: 27 claimers[0x7A48401B0543573D21dfEf15FC54a3E2F599CddF] = 28; // seq: 28 -> tkn_id: 28 claimers[0xd789A1a081553AF9407572711c1163F8A06b4d8F] = 29; // seq: 29 -> tkn_id: 29 claimers[0x498E96c727700a6B7aC2c4EfBd3E9a5DA4F0d137] = 30; // seq: 30 -> tkn_id: 30 claimers[0x7450Cc1b710Afd9B07EECAA19520735e1848479f] = 31; // seq: 31 -> tkn_id: 31 claimers[0x8637576EbDF8b8cb96de6a32C99cb8bDa61d2A11] = 32; // seq: 32 -> tkn_id: 32 claimers[0x77724E749eFB937CE0a78e16E1f1ec5979Cba55a] = 33; // seq: 33 -> tkn_id: 33 claimers[0x3b3D3491f9aE5125f156abA9380aFf62c201054C] = 34; // seq: 34 -> tkn_id: 34 claimers[0x782E60F18e4a3Fc21FF1409d4312ed769f70B1ef] = 35; // seq: 35 -> tkn_id: 35 claimers[0x05C4C65873473C13741c31De2d74005832A0A3d8] = 36; // seq: 36 -> tkn_id: 36 claimers[0xC5E57C099Ed08c882ea1ddF42AFf653e31Ac40df] = 37; // seq: 37 -> tkn_id: 37 claimers[0xe0dC972a92f3b463b43aB29b4F9C960983Bf948F] = 38; // seq: 38 -> tkn_id: 38 claimers[0x4348d40ee12932Aaf0e3412a3aC0598Eb22b96Ad] = 39; // seq: 39 -> tkn_id: 39 claimers[0x75Df0A4a6994AEAa458cfB15863131448fAeDf62] = 40; // seq: 40 -> tkn_id: 40 claimers[0x355e03d40211cc6b6D18ce52278e91566fF29839] = 41; // seq: 41 -> tkn_id: 41 claimers[0x9256EBe5cBcc67E28E2Cd981b835e02590aae7e4] = 42; // seq: 42 -> tkn_id: 42 claimers[0xFf0bAF087F2EE3BbcD2b8aA6560bd5B8F23D99B4] = 43; // seq: 43 -> tkn_id: 43 claimers[0x044bBDc90E1770abD48B6Ede37430b325B6A95EE] = 44; // seq: 44 -> tkn_id: 44 claimers[0x7060FE99b67e37c5fdA833edFe6135580876B996] = 45; // seq: 45 -> tkn_id: 45 claimers[0xaBfc1b7AFD818E1a44539b1EC5021C649b9Dded0] = 46; // seq: 46 -> tkn_id: 46 claimers[0xeec2f0f93e6BC7d13c5E61887aea39d233A0631f] = 47; // seq: 47 -> tkn_id: 47 claimers[0xF6d670C5C0B206f44E93dE811054F8C0b6e15905] = 48; // seq: 48 -> tkn_id: 48 claimers[0x679959449b608AF08d9419fE66D4e985c7d64D96] = 49; // seq: 49 -> tkn_id: 49 claimers[0xF5Dc9930f10Ca038De87C2FDdebe03C10aDeABDC] = 50; // seq: 50 -> tkn_id: 50 claimers[0x07587c046d4d4BD97C2d64EDBfAB1c1fE28A10E5] = 51; // seq: 51 -> tkn_id: 51 claimers[0xc674fFaD8082Aa238F15cd5a91aB1fd68aFEcEaE] = 52; // seq: 52 -> tkn_id: 52 claimers[0xF670B0Ce50B31B5BE40fD8cE84535a7D021775EF] = 53; // seq: 53 -> tkn_id: 53 claimers[0xEec4013a607D720989DB8F464361CdcF2cb7A7BD] = 54; // seq: 54 -> tkn_id: 54 claimers[0xA183B2f9d89367D935EC1Ebd1d33288a7113a971] = 55; // seq: 55 -> tkn_id: 55 claimers[0x42de824dA4C1Af884ebEdaA2352Fd4d4e00445DF] = 56; // seq: 56 -> tkn_id: 56 claimers[0x6F4440719569D61571f50c7e2B33b17E191b0654] = 57; // seq: 57 -> tkn_id: 57 claimers[0xBe671d9b29F218d711404D8F39f830eE14dAAF72] = 58; // seq: 58 -> tkn_id: 58 claimers[0xC7892093FEE029bF01D2b8C02098Cd4864bE3939] = 59; // seq: 59 -> tkn_id: 59 claimers[0x5a6541F3205D510ddB3B6dFD7b5fc5361C6fD47c] = 60; // seq: 60 -> tkn_id: 60 claimers[0xcBde85bF0b88791f902d4c18E4ad5F5CFAf76794] = 61; // seq: 61 -> tkn_id: 61 claimers[0x6A6181794DDDC287F54CF7393d81539Be2899cFd] = 62; // seq: 62 -> tkn_id: 62 claimers[0x70A2907B45A81f53b09976294B99b345B77fD134] = 63; // seq: 63 -> tkn_id: 63 claimers[0x171c3eEd74fcd74881f8Cb1de048C156D8c0EdE4] = 64; // seq: 64 -> tkn_id: 64 claimers[0x9d430D7338FF1E15f889ac90Ca992630F5150e64] = 65; // seq: 65 -> tkn_id: 65 claimers[0xd2C8CC3DcB9C79A4F85Bcad9EF4e0ccf4619d690] = 66; // seq: 66 -> tkn_id: 66 claimers[0x4e79317de3479dC23De1F1A9Ca664651bCAc8A43] = 67; // seq: 67 -> tkn_id: 67 claimers[0x35dF3706eD8779Fc4b401722754867304c11c95D] = 68; // seq: 68 -> tkn_id: 68 claimers[0xD29D862f28331705D432Dfab3f3491372E7295ad] = 69; // seq: 69 -> tkn_id: 69 claimers[0x889769e73f452E10B70414917c4d1fcd0F9a53b8] = 70; // seq: 70 -> tkn_id: 70 claimers[0x8a381C0bB4B2322a455897659cb34BC1395d3124] = 71; // seq: 71 -> tkn_id: 71 claimers[0x5319C3F016C7FC4b6770d4a8C313036da7F61290] = 72; // seq: 72 -> tkn_id: 72 claimers[0xC9D15F4E6f1b37CbF0E8068Ff84B5282edEF9707] = 73; // seq: 73 -> tkn_id: 73 claimers[0x826121D2a47c9D6e71Fd4FED082CECCc8A5381b1] = 74; // seq: 74 -> tkn_id: 74 claimers[0xb12F75B5F95022a54E6BbDd1086691635571911e] = 75; // seq: 75 -> tkn_id: 75 claimers[0xc9C56009DD643c2e6567E83F75A69C8Cc29AdeaC] = 76; // seq: 76 -> tkn_id: 76 claimers[0x40e00884ee94a5143cd9419d5DCA7Ede6730a793] = 77; // seq: 77 -> tkn_id: 77 claimers[0x78F3Aab3E918F2Bf8089EBC3698f78D3a273D6B2] = 78; // seq: 78 -> tkn_id: 78 claimers[0x7e6A5192cF2033c00efA844A353AFE1869bDF94B] = 79; // seq: 79 -> tkn_id: 79 claimers[0x3af46de2aCc78D4d4902a87618d28C0B194d7e63] = 80; // seq: 80 -> tkn_id: 80 claimers[0x0c84d74104Ac83AB98a80FB5e88F06137e842825] = 81; // seq: 81 -> tkn_id: 81 claimers[0x54280007118299877b466875B2aa6B59327DD93c] = 82; // seq: 82 -> tkn_id: 82 claimers[0x26122FE0a9966f1fA4897982782225037B3e490B] = 83; // seq: 83 -> tkn_id: 83 claimers[0xaCcE74f9dD9f3133f160417A8B554CD3Cc8a3B95] = 84; // seq: 84 -> tkn_id: 84 claimers[0xb081c44e699A895f126D09D362B1088826D12963] = 85; // seq: 85 -> tkn_id: 85 claimers[0x86c8283764C402C9E61d916096780014724C8fC9] = 86; // seq: 86 -> tkn_id: 86 claimers[0xC7857556C226b0e61bb18EB8Dd191bE7E1ee8Ad3] = 87; // seq: 87 -> tkn_id: 87 claimers[0xc45e08A07F491e778463460D52c592d11C3f761a] = 88; // seq: 88 -> tkn_id: 88 claimers[0x6F08fdC20c018121c6BE83218C95eBf42A45b571] = 89; // seq: 89 -> tkn_id: 89 claimers[0x073859cdA73a56d92a13DbE2B4e0B34dEF4756e8] = 90; // seq: 90 -> tkn_id: 90 claimers[0xA2531843629b036C6691A63bE5a91291902d42E0] = 91; // seq: 91 -> tkn_id: 91 claimers[0x4C697E1432cB49AC229241b5577284671Bae9d16] = 92; // seq: 92 -> tkn_id: 92 claimers[0x5973FFe2B9608e66A328c87c534e4Bb758618e73] = 93; // seq: 93 -> tkn_id: 93 claimers[0xcdB76A96af6eEC323a0fAC36D852b552f16C5a5F] = 94; // seq: 94 -> tkn_id: 94 claimers[0x23D623D3C6F334f55EF0DDF14FF0e05f1c88A76F] = 95; // seq: 95 -> tkn_id: 95 claimers[0x843D261B740F97BF31d09846F9d96dcC5Fd2a0D0] = 96; // seq: 96 -> tkn_id: 96 claimers[0x81cee999e0cf2DA5b420a5c02649C894F69C86bD] = 97; // seq: 97 -> tkn_id: 97 claimers[0x927a03B6606380147e38E88b1B491c7D29a62eEa] = 98; // seq: 98 -> tkn_id: 98 claimers[0x64F8eF34aC5Dc26410f2A1A0e2b4641189040231] = 99; // seq: 99 -> tkn_id: 99 claimers[0x1cFACa65bF36aE4548c9fB84d4d8A22bfBAA7B84] = 100; // seq: 100 -> tkn_id: 100 claimers[0xa069cD30b87e947Ba78e36e30E485e4926e4d176] = 101; // seq: 101 -> tkn_id: 101 claimers[0x9631200833a348641c5D08C5E146BBBFcD5367D2] = 102; // seq: 102 -> tkn_id: 102 claimers[0xb521154e8f8978f64567FE0FA7359Ab47f7363fA] = 103; // seq: 103 -> tkn_id: 103 claimers[0x9b534B88E83013B2fCE9Bb5BA813a6B96707cc8F] = 104; // seq: 104 -> tkn_id: 104 claimers[0xAaC5Ca3FEe00833ACC563FB41048179ACA8b9c07] = 105; // seq: 105 -> tkn_id: 105 claimers[0xeb0f5dce389A86a64c71F91eCE001067A9cD574E] = 106; // seq: 106 -> tkn_id: 106 claimers[0xA735E424fD55a18148BB5FE1f128Fbe30B7b56DB] = 107; // seq: 107 -> tkn_id: 107 claimers[0x85222954e2742ACe2F14f23E7694Ec1AbFD00F49] = 108; // seq: 108 -> tkn_id: 108 claimers[0x601379eF00F1879F13E4b498133b560b06bfeC36] = 109; // seq: 109 -> tkn_id: 109 claimers[0xD0c72d410D06C4C4A70Ff96beaB8432071F4d3B8] = 110; // seq: 110 -> tkn_id: 110 claimers[0xC1c2E49a3223E56f07068d836fd354e7269cBD78] = 111; // seq: 111 -> tkn_id: 111 claimers[0x88bf9430fE41AC4Dd87BeC4ba3C44012f7876e55] = 112; // seq: 112 -> tkn_id: 112 claimers[0xB8F69EC91b068E702BafCBf282feca36c585a539] = 113; // seq: 113 -> tkn_id: 113 claimers[0x6E03a79F43A6bd3b77531603990e9b39456389Ed] = 114; // seq: 114 -> tkn_id: 114 claimers[0xf522F0672107333dC549A8AcEDF62746844b65ce] = 115; // seq: 115 -> tkn_id: 115 claimers[0x4A74407858aeF6532ed771cFBb154829c53ABc47] = 116; // seq: 116 -> tkn_id: 116 claimers[0xa10e13c392EBB57adD9f23aa3792ac05D0d6dE7E] = 117; // seq: 117 -> tkn_id: 117 claimers[0xB0C054B2F0CA15fEadD4172037dC1e93b113AcC9] = 118; // seq: 118 -> tkn_id: 118 claimers[0xdC30CABcfBD95Ea2D5675002B5b00a2C499FAc12] = 119; // seq: 119 -> tkn_id: 119 claimers[0xc6c1E852ECCE4Ce5a0C93F0E68063202dA81202b] = 120; // seq: 120 -> tkn_id: 120 claimers[0x9cf39Ad673E95F292CD2060A36AE552227198a0C] = 121; // seq: 121 -> tkn_id: 121 claimers[0xbE20DFb456b7E81f691A8445d073e56602E3cefa] = 122; // seq: 122 -> tkn_id: 122 claimers[0xb29D3652ebe85C4303c87d3B728C511c4b0943E3] = 123; // seq: 123 -> tkn_id: 123 claimers[0x8CFAb48f1B6328eEAF6abaFa5Ba780550bC5109D] = 124; // seq: 124 -> tkn_id: 124 claimers[0x26cF22300E6B89437e7EEc90Bf56CadDBF4bB322] = 125; // seq: 125 -> tkn_id: 125 claimers[0x9B39dadCD266337e8F7C91dCA03fF61484a8882b] = 126; // seq: 126 -> tkn_id: 126 claimers[0x3E5e35208a84eF21d441a5365BE09BF65Af2f709] = 127; // seq: 127 -> tkn_id: 127 claimers[0x630098B792120d38dF22ecE88378d0676A3ce48c] = 128; // seq: 128 -> tkn_id: 128 claimers[0x70c5d2942b12C0aa6103129B18B3503c0610408e] = 129; // seq: 129 -> tkn_id: 129 claimers[0x91Fa472FB12Ef104d649facCE00e3bA43dE57A8D] = 130; // seq: 130 -> tkn_id: 130 claimers[0xCA755A9bD26148F18B4D2e316966E9fE915d46aC] = 131; // seq: 131 -> tkn_id: 131 claimers[0x6d6AB746901f8F7de018DCc417b6D417725B41aF] = 132; // seq: 132 -> tkn_id: 132 claimers[0x42a2D911F4C526233F203D2d156Aa5146044cB7e] = 133; // seq: 133 -> tkn_id: 133 claimers[0x0B01fE5189d95c0fa890fd6b431928B5dF58D027] = 134; // seq: 134 -> tkn_id: 134 claimers[0x84b8bfD62Bb591976429dC060ABd9bfD0eD6508B] = 135; // seq: 135 -> tkn_id: 135 claimers[0xe0d30e989810470A74Ab2D7EBaD424d76FFA8cdd] = 136; // seq: 136 -> tkn_id: 136 claimers[0x390b07DC402DcFD54D5113C8f85d90329A0141ef] = 137; // seq: 137 -> tkn_id: 137 claimers[0xfbF30C01041A372Be48217FE201a30470b0b3Ac2] = 138; // seq: 138 -> tkn_id: 138 claimers[0x973b79656F9A2B6d3F9B04E93F3C340C9f7b4C6C] = 139; // seq: 139 -> tkn_id: 139 claimers[0xDf5B7bE800A5A7A67e887C2f677Cd29a7a05b6E1] = 140; // seq: 140 -> tkn_id: 140 claimers[0x3720c491F4564429154862285E7F1f830E059065] = 141; // seq: 141 -> tkn_id: 141 claimers[0x6046D412B45dACe6c963C7c3C892AD951EC97e57] = 142; // seq: 142 -> tkn_id: 142 claimers[0x4b4E4A8bCB923783A401dc80766D7aBf5631dC0d] = 143; // seq: 143 -> tkn_id: 143 claimers[0x4460dD70a847481f63e015b689a9E226E8bD5b71] = 144; // seq: 144 -> tkn_id: 144 claimers[0x7d2D2E04f1Db8B54746eFA719CB62F32A6C84a84] = 145; // seq: 145 -> tkn_id: 145 claimers[0xdFA56E55811b6F9548F4cB876CC796a6A4071993] = 146; // seq: 146 -> tkn_id: 146 claimers[0xceCb7E46Ed153BfC38961b27Da43f8fddCbEF210] = 147; // seq: 147 -> tkn_id: 147 claimers[0xCffA068214d25B3D75f4676302C0E9390cCBBbEb] = 148; // seq: 148 -> tkn_id: 148 claimers[0x0873E406b948314E516eF6B6C618ba42B72b46C6] = 149; // seq: 149 -> tkn_id: 149 claimers[0xdC67aF6B6Ee64eec179135103b62FB68360Af860] = 150; // seq: 150 -> tkn_id: 150 claimers[0xDB7b6AA8240f527c35FD8E8c5e3a9eFc7359341d] = 151; // seq: 151 -> tkn_id: 151 claimers[0xF962e687562999a127a5b5A2ECBE99d0601564Eb] = 152; // seq: 152 -> tkn_id: 152 claimers[0x6Fa98A4254c7E9Ec681cCeb3Cb8D64a70Dbea256] = 153; // seq: 153 -> tkn_id: 153 claimers[0x5EFACb9C824eb8b0acE54a0054B7924e6c9eFaf0] = 154; // seq: 154 -> tkn_id: 154 claimers[0xaB59d30a5CE7cD360Cc333235a1deA7e3Ba3f2a1] = 155; // seq: 155 -> tkn_id: 155 claimers[0x8f1b33E27b6135BFC87Cda27Ebc90025f039F5fe] = 156; // seq: 156 -> tkn_id: 156 claimers[0x49e03A6C22602682B3Fbecc5B181F7649b1DB6Ad] = 157; // seq: 157 -> tkn_id: 157 claimers[0x0A3e7c501d685dcc9d65119e3f3A9f8F4875f8F6] = 158; // seq: 158 -> tkn_id: 158 claimers[0x2fb0d4F09e5F7E399354D8DbF602c871b84c081F] = 159; // seq: 159 -> tkn_id: 159 claimers[0xe2D18861c892f4eFbaB6b2749e2eDe16aF458A94] = 160; // seq: 160 -> tkn_id: 160 claimers[0x03aEC62437E9f1485410654E5daf4f5ad707f395] = 161; // seq: 161 -> tkn_id: 161 claimers[0xB7493191Dbf9f687D3e019cDaaDc3C52d95C87EF] = 162; // seq: 162 -> tkn_id: 162 claimers[0x6F6ed604bc1A64a385978c99310D2fc0758AF29e] = 163; // seq: 163 -> tkn_id: 163 claimers[0xF9A508D543416f530295048985e7a7C295b7F957] = 164; // seq: 164 -> tkn_id: 164 claimers[0xfB89fBaFE753873386D6E46dB066c47d8Ef857Fa] = 165; // seq: 165 -> tkn_id: 165 claimers[0xF81d36Dd1406f937323aC6C43F1be8D3b5Fd8d30] = 166; // seq: 166 -> tkn_id: 166 claimers[0x88591bc3054339708bA101116E04f0359232962F] = 167; // seq: 167 -> tkn_id: 167 claimers[0xC707b5BD687749e7e418eBDd79a387904025B02e] = 168; // seq: 168 -> tkn_id: 168 claimers[0x2cBC074df0dC03defDd1d3D985B4B1a961DB5415] = 169; // seq: 169 -> tkn_id: 169 claimers[0xf4BD7C08403250BeE1fD9D819d9DF0Ae956C3ceb] = 170; // seq: 170 -> tkn_id: 170 claimers[0x442670b5f713c61Eb9FcB4e27fcA6505815c9861] = 171; // seq: 171 -> tkn_id: 171 claimers[0xBB8135f8136425f7af9De8ee926C58D09E9525eE] = 172; // seq: 172 -> tkn_id: 172 claimers[0x5e0819Db5c0b3952149150310945752ae22745B0] = 173; // seq: 173 -> tkn_id: 173 claimers[0x3d359BE336fa4760d4399230F4067e04D1b9ed7B] = 174; // seq: 174 -> tkn_id: 174 claimers[0x136BE67011Dd5F97dcdba8d0F3b5B650aCdcaE5C] = 175; // seq: 175 -> tkn_id: 175 claimers[0x24f39151D6d8A9574D1DAC49a44F1263999D0dda] = 176; // seq: 176 -> tkn_id: 176 claimers[0x1c458B84B81B5Cc1ed226c05873E75e2Ae1dCA90] = 177; // seq: 177 -> tkn_id: 177 claimers[0xFab6e024A48d1d56D3A030E9ecC6f17F3122fB73] = 178; // seq: 178 -> tkn_id: 178 claimers[0x47b0A090Ea0D040F65F3f2Ab0fFc7824C924E144] = 179; // seq: 179 -> tkn_id: 179 claimers[0xAd2D729Ad42373A3cad2ef405197E2550f4af860] = 180; // seq: 180 -> tkn_id: 180 claimers[0x62cfc31f574F8ec9719d719709BCCE9866BEcaCd] = 181; // seq: 181 -> tkn_id: 181 claimers[0xe6BB1bEBF6829ca5240A80F7076E4CFD6Ee540ae] = 182; // seq: 182 -> tkn_id: 182 claimers[0x94d3B13745c23fB57a9634Db0b6e4f0d8b5a1053] = 183; // seq: 183 -> tkn_id: 183 claimers[0x1eF576f02107BEc448d74DcA749964013A8531e7] = 184; // seq: 184 -> tkn_id: 184 claimers[0x9b2D76f2E5E92b2C78C6e2ce07c6f86B95091964] = 185; // seq: 185 -> tkn_id: 185 claimers[0x06e9f7674a2cC609adA8dc6777f07385A238006a] = 186; // seq: 186 -> tkn_id: 186 claimers[0xC5b09ee88Cfb4FF08C8769A89B0c314FC1636b19] = 187; // seq: 187 -> tkn_id: 187 claimers[0x6595cfA52F9F91bA319386c4549039581259D57A] = 188; // seq: 188 -> tkn_id: 188 claimers[0x06B40D42b10ADBEa8CA0f12Db1E6E1e11632EB0d] = 189; // seq: 189 -> tkn_id: 189 claimers[0x98a784132CF101E8Cd2764ded4c2F246325F1fe6] = 190; // seq: 190 -> tkn_id: 190 claimers[0x693Ab9656C70BfA41443A84d4c96eAFb82d382B4] = 191; // seq: 191 -> tkn_id: 191 claimers[0xBC0147233b8a028Ed4fbcEa6CF473e30EdcfabD3] = 192; // seq: 192 -> tkn_id: 192 claimers[0xd6fE3581974330145d703B1914a6A441512992A7] = 193; // seq: 193 -> tkn_id: 193 claimers[0x935016109bFA23F810112F5Fe2862cB0c5F26bd2] = 194; // seq: 194 -> tkn_id: 194 claimers[0x2E5F97Ce8b95Ffb5B007DA1dD8fE0399679a6F23] = 195; // seq: 195 -> tkn_id: 195 claimers[0xF0fE8DA6C23c4772455F49102947157A56d22C76] = 196; // seq: 196 -> tkn_id: 196 claimers[0x03890EeB6303C86A4b44218Fbe8e8811fab0CB43] = 197; // seq: 197 -> tkn_id: 197 claimers[0x6A2e363b31D5fd9556765C8f37C1ddd2Cd480fA3] = 198; // seq: 198 -> tkn_id: 198 claimers[0x4744e7077Cf68Bca4feFFc42f3E8C1dbDF59CBaa] = 199; // seq: 199 -> tkn_id: 199 claimers[0xcEa283786F5f676d9A63599AF98D850eFEB95BaD] = 200; // seq: 200 -> tkn_id: 200 claimers[0xcb1C261dc5EF5D611c7E2F83653eA0e744654089] = 201; // seq: 201 -> tkn_id: 201 claimers[0x970393Db17dde3b234A4C17D2Be2Bad3A34249f7] = 202; // seq: 202 -> tkn_id: 202 claimers[0x84414ef56970b4F6B44673cdeC093cEE916Ad471] = 203; // seq: 203 -> tkn_id: 203 claimers[0x237b3c12D93885b65227094092013b2a792e92dd] = 204; // seq: 204 -> tkn_id: 204 claimers[0x611b3f03fc28Eb165279eADeaB258388D125e8BC] = 205; // seq: 205 -> tkn_id: 205 claimers[0x20DC3e9ECcc11075A055Aa631B64aF4b0d6dc571] = 206; // seq: 206 -> tkn_id: 206 claimers[0x5703Cf5FCE210caA2dbbFB6e88B77d126683fA76] = 207; // seq: 207 -> tkn_id: 207 claimers[0x1850AB1344493b8f66a0780c6806fe57AE7a13B4] = 208; // seq: 208 -> tkn_id: 208 claimers[0x710A169B822Bf51b8F8E6538c63deD200932BB29] = 209; // seq: 209 -> tkn_id: 209 claimers[0xA37EDEE06096F9fbA272B4943066fcd28d39Dc2d] = 210; // seq: 210 -> tkn_id: 210 claimers[0xb42FeE033AD3809cf9D1d6C1f922478F1C4A652c] = 211; // seq: 211 -> tkn_id: 211 claimers[0xebfc11fE400f2DF40B8b669845d4A3479192e859] = 212; // seq: 212 -> tkn_id: 212 claimers[0xf18210B928bc3CD75966329429131a7fD6D1b667] = 213; // seq: 213 -> tkn_id: 213 claimers[0x24d32644137e2Bc36f3d039977C83e5cD489F809] = 214; // seq: 214 -> tkn_id: 214 claimers[0x99dcfb0E41BEF20Dc9661905D4ABBD92267095Ee] = 215; // seq: 215 -> tkn_id: 215 claimers[0x1e390D5391B98F3a2d489F1a7CA646F8F336491C] = 216; // seq: 216 -> tkn_id: 216 claimers[0xBECb82002565aa5C6c4722A473AdDb5e2c909f9C] = 217; // seq: 217 -> tkn_id: 217 claimers[0x721D12Fc93F4E6509D388BF79EcE34CDcB775d62] = 218; // seq: 218 -> tkn_id: 218 claimers[0x108fF5724eC28D6066855899c4a422De4E0ae6a2] = 219; // seq: 219 -> tkn_id: 219 claimers[0x44e02B37c29d3689d95Df1C87e6153CC7e2609AA] = 220; // seq: 220 -> tkn_id: 220 claimers[0x41e309Fb027372e28907c0FCAD78DD26460Dd4c2] = 221; // seq: 221 -> tkn_id: 221 claimers[0xb827857235d4eACc540A79e9813c80E351F0dC06] = 222; // seq: 222 -> tkn_id: 222 claimers[0x8e27ac9EA29ecFfC575BbC73502D3c18848e57a0] = 223; // seq: 223 -> tkn_id: 223 claimers[0x4Fa0DE7b23BcF1e8714E0c91f7B856e5Ff99c6D0] = 224; // seq: 224 -> tkn_id: 224 claimers[0x8f6869697ab3ee78C3480D3D36B112025373438C] = 225; // seq: 225 -> tkn_id: 225 claimers[0x20fac303520CB60860065871FA213DE09D10A009] = 226; // seq: 226 -> tkn_id: 226 claimers[0x61603cD19B067B417284cf9fC94B3ebF5703824a] = 227; // seq: 227 -> tkn_id: 227 claimers[0x468769E894f0894A44B50AE363395793b17F11b3] = 228; // seq: 228 -> tkn_id: 228 claimers[0xE797B7d15f06733b9ceCF87656aD5f56945A1eBf] = 229; // seq: 229 -> tkn_id: 229 claimers[0x6592aB22faD2d91c01cCB4429F11022E2595C401] = 230; // seq: 230 -> tkn_id: 230 claimers[0x68cf193fFE134aD92C1DB0267d2062D01FEFDD06] = 231; // seq: 231 -> tkn_id: 231 claimers[0x7988E3ae0d19Eff3c8bC567CA0438F6Df3cB2813] = 232; // seq: 232 -> tkn_id: 232 claimers[0xd85bCc93d3A3E89303AAaF43c58E624D24160455] = 233; // seq: 233 -> tkn_id: 233 claimers[0xc34F0F4cf2ffD0F91DB7DFBd81B432580019F1a8] = 234; // seq: 234 -> tkn_id: 234 claimers[0xbf9fe0f5cAeE6967C874e108fE69969E09fa156c] = 235; // seq: 235 -> tkn_id: 235 claimers[0x1eE73ad65581d5Efe7430dcb5a653d5015332454] = 236; // seq: 236 -> tkn_id: 236 claimers[0xFfcef83Eb7Dd0Ec7770Ac08D8f11a87fA87E12d9] = 237; // seq: 237 -> tkn_id: 237 claimers[0x6Acb64A76e62D433a9bDCB4eeA8343Be8b3BeF48] = 238; // seq: 238 -> tkn_id: 238 claimers[0x8eCAD8Da3D1F5E0E91e8A55dd979A863CFdFCee7] = 239; // seq: 239 -> tkn_id: 239 claimers[0x572f60c0b887203324149D9C308574BcF2dfaD82] = 240; // seq: 240 -> tkn_id: 240 claimers[0xcCf70d7637AEbF9D0fa22e542Ac4082569f4ED5A] = 241; // seq: 241 -> tkn_id: 241 claimers[0x9de35B6bE7B911DEA9A4DE84E9b8a34038c6ECea] = 242; // seq: 242 -> tkn_id: 242 claimers[0x1c05141A1A0d425E92653ADfefDaFaec40681bdB] = 243; // seq: 243 -> tkn_id: 243 claimers[0x79Bc1a648aa95618bBeB3BFb2a15E3415C52FF86] = 244; // seq: 244 -> tkn_id: 244 claimers[0x5f3E1bf780cA86a7fFA3428ce571d4a6D531575D] = 245; // seq: 245 -> tkn_id: 245 claimers[0xcD426623A98E22e76758a98F7A85d4499973b37F] = 246; // seq: 246 -> tkn_id: 246 claimers[0x674901AdeB413C126a069402E751ba80F2e2152e] = 247; // seq: 247 -> tkn_id: 247 claimers[0x111f5B33389BBA60c3b16a6ae891F7D281762369] = 248; // seq: 248 -> tkn_id: 248 claimers[0x51679136e1a3407912f8fA131Bc5F611c52d9fEe] = 249; // seq: 249 -> tkn_id: 249 claimers[0xB955E56849E0875E44074C56F21CF009E2B8B6c4] = 250; // seq: 250 -> tkn_id: 250 claimers[0x3D7af9ABecFe6BdD60C8dcDFaF3b83f92DB06885] = 251; // seq: 251 -> tkn_id: 251 claimers[0x836B55F9A4A39f5b39b372a0943C782cE48C0Ef8] = 252; // seq: 252 -> tkn_id: 252 claimers[0x6412dDF748608073034090646D37D5E4CE71a4CE] = 253; // seq: 253 -> tkn_id: 253 claimers[0x924fD2357ACe38052C5f73c0bFDCd2666b02F908] = 254; // seq: 254 -> tkn_id: 254 claimers[0xFA3C94ab4Ba1fD92bf8331C7cC6aabe50074D08D] = 255; // seq: 255 -> tkn_id: 255 claimers[0xE75a37358127B089Ae9E2E23322E23bAE28ea3D9] = 256; // seq: 256 -> tkn_id: 256 claimers[0xA2Eef2A6EB56118C910101d53a860F62cf2Ec903] = 257; // seq: 257 -> tkn_id: 257 claimers[0xeA83A7a09229F7921D9a72A1f5Ff03aA5bA096E2] = 258; // seq: 258 -> tkn_id: 258 claimers[0xA0C9D9d21b2CB0400D59C70AC6CEA3e7a81F1AA7] = 259; // seq: 259 -> tkn_id: 259 claimers[0x295Cf1759Af15bE4b81D12d6Ee41C3D9A30Ad410] = 260; // seq: 260 -> tkn_id: 260 claimers[0xb8b52400D83e12e61Ea0D00A1fcD7e1E2F8d5f83] = 261; // seq: 261 -> tkn_id: 261 claimers[0x499E5938F54C3769c4208F1Bc58AEAdF13A1FF8B] = 262; // seq: 262 -> tkn_id: 262 claimers[0x2F48e68D0e507AF5a278130d375AA39f4966E452] = 263; // seq: 263 -> tkn_id: 263 claimers[0xCAB03A436F0af91cE68594f45A95D8f7f5004A14] = 264; // seq: 264 -> tkn_id: 264 claimers[0x8ee4219378c25ca2023690A71f2d337a29d67A89] = 265; // seq: 265 -> tkn_id: 265 claimers[0x00737ac98C3272Ee47014273431fE189047524e1] = 266; // seq: 266 -> tkn_id: 266 claimers[0x29175A067860f9BDBDb411dB0A76F5EbDa5544fF] = 267; // seq: 267 -> tkn_id: 267 claimers[0x5bb3e01c8dDCE82AF3f6e76f46d8965176A2daEe] = 268; // seq: 268 -> tkn_id: 268 claimers[0x47F2F66729171D0b40E9fDccAbBae5d8ec2d2065] = 269; // seq: 269 -> tkn_id: 269 claimers[0x86017110100312E0C2cCc0c14A58C4bf830a7EF6] = 270; // seq: 270 -> tkn_id: 270 claimers[0x26ceA6C7a525c17027750d315aBa267b7B0bB209] = 271; // seq: 271 -> tkn_id: 271 claimers[0xa0E609533840b910208BFb4b711df62C4a6247D2] = 272; // seq: 272 -> tkn_id: 272 claimers[0x35570f310697a5C687Eb37b63B4Ae696cE0d14C0] = 273; // seq: 273 -> tkn_id: 273 claimers[0x9e0eD477f110cb75453181Cd4261D40Fa7396056] = 274; // seq: 274 -> tkn_id: 274 claimers[0xd53b873683Df491553eea6a069770144Ad30F3A9] = 275; // seq: 275 -> tkn_id: 275 claimers[0x164934C2A068932b83Bbf81A66FF01825F2dc5e1] = 276; // seq: 276 -> tkn_id: 276 claimers[0x3eC7e5215984bE5FebA858c9502BD563bB135B1a] = 277; // seq: 277 -> tkn_id: 277 claimers[0x587A050489516119D39C228519536b561ff3fA93] = 278; // seq: 278 -> tkn_id: 278 claimers[0x8767149b0520f2e6A56eed33166Ff8484B3Ac058] = 279; // seq: 279 -> tkn_id: 279 claimers[0x49A3f1200730D84551d13FcBC121A6405eDe4D56] = 280; // seq: 280 -> tkn_id: 280 claimers[0xc206014aAf21E07ae5868730098D919F99d79616] = 281; // seq: 281 -> tkn_id: 281 claimers[0x38878917a3EC081c4C78dde8Dd49F43eE10CAf12] = 282; // seq: 282 -> tkn_id: 282 claimers[0x2FfF3F5b8560407781dFCb04a068D7635A179EFE] = 283; // seq: 283 -> tkn_id: 283 claimers[0x56256Df5A901D0B566C1944D4307E2e4Efb23838] = 284; // seq: 284 -> tkn_id: 284 claimers[0x280b8503E2927060120391baf51733E357B190eb] = 285; // seq: 285 -> tkn_id: 285 claimers[0x8C0Da5cc7524Ed8a3f6C79B07aC43081F5A54975] = 286; // seq: 286 -> tkn_id: 286 claimers[0xdE4f8a84929bF5185c03697444D8ddb8ae852116] = 287; // seq: 287 -> tkn_id: 287 claimers[0x8BB01a948ABAC1758E3ED59621f1CD7d90C8FF8C] = 288; // seq: 288 -> tkn_id: 288 claimers[0x59B7759338666625957B1Ef4482DeBd5da1a6091] = 289; // seq: 289 -> tkn_id: 289 claimers[0xD63ba61D2f3C3f108a3C54B987e9435aFB715Cc5] = 290; // seq: 290 -> tkn_id: 290 claimers[0x9f8eF2849133286860A8216cA11359381706Fa4a] = 291; // seq: 291 -> tkn_id: 291 claimers[0x125EaE40D9898610C926bb5fcEE9529D9ac885aF] = 292; // seq: 292 -> tkn_id: 292 claimers[0xB4Ae4070a56624A7c99B438664853D0f454BE116] = 293; // seq: 293 -> tkn_id: 293 claimers[0xb651Ad89b16cca4bD6FE8b4C0Bc3481b15F779c1] = 294; // seq: 294 -> tkn_id: 294 claimers[0x0F193c91a7F3B41Db23d1ab0eeD96003b9f62Ca8] = 295; // seq: 295 -> tkn_id: 295 claimers[0x09A221b474B51e530f20C727d519e243207E128B] = 296; // seq: 296 -> tkn_id: 296 claimers[0x6ea3A5faA3788814262bB1b3a5c0b82d3d24fCA6] = 297; // seq: 297 -> tkn_id: 297 claimers[0xfDf9EAfF221dB644Eb5acCA77Fe72B6553FFbDc9] = 298; // seq: 298 -> tkn_id: 298 claimers[0xb6ccBc7252a4576387d7AF08E603A330950477c5] = 299; // seq: 299 -> tkn_id: 299 claimers[0xB248B3309e31Ca924449fd2dbe21862E9f1accf5] = 300; // seq: 300 -> tkn_id: 300 claimers[0x53d9Bfc075ed4Adb207ed0C95f230A2387Bb001c] = 301; // seq: 301 -> tkn_id: 301 claimers[0x36870b333D653A201d3D7a1209937fE229B7926a] = 302; // seq: 302 -> tkn_id: 302 claimers[0x8A289c7CA7224bEf1Acf234bcD92bF1b8EE5e2D4] = 303; // seq: 303 -> tkn_id: 303 claimers[0xC3aB2C2Eb604F159C842D9cAdaBBa2d6254c43d5] = 304; // seq: 304 -> tkn_id: 304 claimers[0x90C4BF2bd887E0AbC40Fb3f1fAd0d294eBb18146] = 305; // seq: 305 -> tkn_id: 305 claimers[0x0130F60bFe7EA24027eBa9894Dd4dAb331885209] = 306; // seq: 306 -> tkn_id: 306 claimers[0x83c4224A765dEE2Fc903dDed4f9A2046Ba7891E2] = 307; // seq: 307 -> tkn_id: 307 claimers[0xA86CB26efc0Cb9d0aC53a2a56292f4BCDfEa6E1a] = 308; // seq: 308 -> tkn_id: 308 claimers[0x031bE1B4fEe66C3cB66DE265172F3567a6CAb2Eb] = 309; // seq: 309 -> tkn_id: 309 claimers[0x5402C9674B5918B803A2826CCF4CE5af813fCd97] = 310; // seq: 310 -> tkn_id: 310 claimers[0xb14ae50038abBd0F5B38b93F4384e4aFE83b9350] = 311; // seq: 311 -> tkn_id: 311 claimers[0xb200d463bCD09CE93454A394a91573DcDe76Bc28] = 312; // seq: 312 -> tkn_id: 312 claimers[0x3a2C5863e401093F9F994Aa989DDFE5F3a154AbD] = 313; // seq: 313 -> tkn_id: 313 claimers[0x3cB704A5FB4428796b728DF7e4CbC67BCA1497Ae] = 314; // seq: 314 -> tkn_id: 314 claimers[0x9BEcaC41878CA0a280Edd9A6360e3beece1a21Bb] = 315; // seq: 315 -> tkn_id: 315 claimers[0x8a382bb6BF2008492268DEdC549B6Cf189a067B5] = 316; // seq: 316 -> tkn_id: 316 claimers[0x8956CBFB070e6fdf8FF8e94DcEDD665902707Dda] = 317; // seq: 317 -> tkn_id: 317 claimers[0x21B9c3830ef962aFA00e4f45d1618F61Df99C404] = 318; // seq: 318 -> tkn_id: 318 claimers[0x48A6ab900eE882f02649f565419b96C32827E29E] = 319; // seq: 319 -> tkn_id: 319 claimers[0x15041371A7aD0a8a97e5A448804dD33FD8DdE233] = 320; // seq: 320 -> tkn_id: 320 claimers[0xA9786dA5d3ABb6C404b79DF28b7f402E58eF7c5B] = 321; // seq: 321 -> tkn_id: 321 claimers[0xea0Ca6DAF5019935ecd3693688941Bdbd4A510b4] = 322; // seq: 322 -> tkn_id: 322 claimers[0xD40356b1304CD0c7Ae2a07ea45917552001b6ed9] = 323; // seq: 323 -> tkn_id: 323 claimers[0x4622fc2DaB3E3E4e1c2d67B8E1Ecf0c63b517d80] = 324; // seq: 324 -> tkn_id: 324 claimers[0xA63328aE7c2Da36133D1F2ecFB9074403667EfE4] = 325; // seq: 325 -> tkn_id: 325 claimers[0x86fce8cB12e663eD626b20E48F1e9095e930Bfa3] = 327; // seq: 326 -> tkn_id: 327 claimers[0xC28Ac85a4A2b5C7B99cA997B9c4919a7f300A2DA] = 328; // seq: 327 -> tkn_id: 328 claimers[0xCbc3906EFE25eD7CF06265f6B02e83dB67eF41AC] = 329; // seq: 328 -> tkn_id: 329 claimers[0xC64E4d5Ecda0b4D8d9255340c9E3B138c846F17F] = 330; // seq: 329 -> tkn_id: 330 claimers[0x3a434BBF72AF14Ae7cBf25c5cFA19Afe6A25510c] = 331; // seq: 330 -> tkn_id: 331 claimers[0xEC712Ce410df07c9a5a38954d1A85520410b8b83] = 332; // seq: 331 -> tkn_id: 332 claimers[0x640Ea12876aE881c578ab5C953F30e6cA2F6b51A] = 333; // seq: 332 -> tkn_id: 333 claimers[0x266EEC4B2968fd655C362B1D1c5a9269caD4aA42] = 334; // seq: 333 -> tkn_id: 334 claimers[0x79ff9938d22D39d6FA7E774637FA6D5cfc0897Cc] = 335; // seq: 334 -> tkn_id: 335 claimers[0xE513dE08500025E9a15E0cb54B232169e5c169BC] = 336; // seq: 335 -> tkn_id: 336 claimers[0xe7F032d734Dd90F2011E46170493f4Ad335C583f] = 337; // seq: 336 -> tkn_id: 337 claimers[0x20a6Dab0c262c28CD9ed6F96A08309220a60601A] = 338; // seq: 337 -> tkn_id: 338 claimers[0xB7da649e07D3C3406427124672bCf3318E4eAD88] = 339; // seq: 338 -> tkn_id: 339 claimers[0xA3D4f816c0deB4Da228D931D419cE2Deb7A362a8] = 340; // seq: 339 -> tkn_id: 340 claimers[0xDd0A2bE389cfc5f1Eb7BDa07147F3ddEa5692821] = 341; // seq: 340 -> tkn_id: 341 claimers[0x1C4Cdcd7f746Dd1d513fae4eBdC9abbca5068924] = 342; // seq: 341 -> tkn_id: 342 claimers[0xf13D7625bf1838c14Af331c5A5014Aea39CC9A8c] = 343; // seq: 342 -> tkn_id: 343 claimers[0xe2C05bB4ffAFfcc3d32039C9153b2bF8aa1C0613] = 344; // seq: 343 -> tkn_id: 344 claimers[0xB9e39A55b80f449cB847Aa679807b7e3309d22C3] = 345; // seq: 344 -> tkn_id: 345 claimers[0x2Bd69F9dFAf984aa97c2f443F4CAa4067B223f1A] = 346; // seq: 345 -> tkn_id: 346 claimers[0xeDf32B8F98D464b9Eb29C74202e6Baae28134fC7] = 347; // seq: 346 -> tkn_id: 347 claimers[0x59aD1737E02556E64487969c844646Dd3B451251] = 348; // seq: 347 -> tkn_id: 348 claimers[0x6895335Bbef92D7cE00465Ebe625fb84cc5fEc2F] = 349; // seq: 348 -> tkn_id: 349 claimers[0xbcBa4F18f391b9E7914E586a7477fbf56E42e90e] = 350; // seq: 349 -> tkn_id: 350 claimers[0x4fee40110623aD02BA4d76c76157D01e22DFbA72] = 351; // seq: 350 -> tkn_id: 351 claimers[0xa8f530a2F1cc7eCeba848BD089ffA923873a835e] = 352; // seq: 351 -> tkn_id: 352 claimers[0xC4b1bb0c1c8c29E234F1884b7787c7e14E1bC0a1] = 353; // seq: 352 -> tkn_id: 353 claimers[0xae3d939ffDc30837ba1b1fF24856e1249cDda61D] = 354; // seq: 353 -> tkn_id: 354 claimers[0x79d39642A48597A9943Cc64432bE1D50F25EFb2b] = 355; // seq: 354 -> tkn_id: 355 claimers[0x65772909024899817Fb7333EC50e4B05534e3dB1] = 356; // seq: 355 -> tkn_id: 356 claimers[0xce2C6c7c40bCe8718786484561a20fbE71416F9f] = 357; // seq: 356 -> tkn_id: 357 claimers[0x7777515751843e7cdcC47E10833E159c47777777] = 358; // seq: 357 -> tkn_id: 358 claimers[0x783a108e6bCD910d476aF96b5A49f54fE379C0eE] = 359; // seq: 358 -> tkn_id: 359 claimers[0xabF552b23902ccC9B1A36512cFaC9869a15C76F6] = 360; // seq: 359 -> tkn_id: 360 claimers[0x16c3576d3c85CBC564ac79bf5F48512ee42054f6] = 361; // seq: 360 -> tkn_id: 361 claimers[0x178025dc029CAA1ff1fEe4Bf4d2b60437ebE661c] = 362; // seq: 361 -> tkn_id: 362 claimers[0x68F38334ca94956AfC2DE794A1E8536eb055bECB] = 363; // seq: 362 -> tkn_id: 363 claimers[0x276A235D7822694C9738f441C777938eb6Dd2a7b] = 364; // seq: 363 -> tkn_id: 364 claimers[0xc7B5D7057BB3A77d8FFD89D3065Ad14E1E9deD7c] = 365; // seq: 364 -> tkn_id: 365 claimers[0xCf57A3b1C076838116731FDe404492D9d168747A] = 366; // seq: 365 -> tkn_id: 366 claimers[0x7eea2a6FEA12a60b67EFEAf4DbeCf028A2F41a2d] = 367; // seq: 366 -> tkn_id: 367 claimers[0xa72ce2426D395380756401fCA476cC6C3CF47354] = 368; // seq: 367 -> tkn_id: 368 claimers[0x5CaF975D380a6f8A4f25Dc9b5A1fC41eb714eF7C] = 369; // seq: 368 -> tkn_id: 369 claimers[0x764d8B7F4d75803008ACaec24745D978A7dF84D6] = 370; // seq: 369 -> tkn_id: 370 claimers[0x0BDfAA5444Eb0fd5E03bCB1ab34e10044971bF39] = 371; // seq: 370 -> tkn_id: 371 claimers[0x0DAddc0280b9B312c56d187BBBDDAFDcdB68Fe02] = 372; // seq: 371 -> tkn_id: 372 claimers[0x299B907233549Fa565d1C8D92429E2c6182F13B8] = 373; // seq: 372 -> tkn_id: 373 claimers[0xA30C27Bcc7A75045385941C7cF9415893ff45b1A] = 374; // seq: 373 -> tkn_id: 374 claimers[0x4E2ECa32c15389F8da0883d11E11d490A3e06d4D] = 375; // seq: 374 -> tkn_id: 375 claimers[0x9318Db19966B03fe3b2DC6A4A59d46d8C98f7c9f] = 376; // seq: 375 -> tkn_id: 376 claimers[0x524b7c9B4cA33ba72445DFd2d6404C81d8D1F2E3] = 377; // seq: 376 -> tkn_id: 377 claimers[0xB862D5e30DE97368801bDC24A53aD90F56a9C068] = 378; // seq: 377 -> tkn_id: 378 claimers[0x53C2A37BEef67489f0a19890F5fEb2Fc53384C72] = 379; // seq: 378 -> tkn_id: 379 claimers[0xe926545EA364a95473905e882f8559a091FD7383] = 380; // seq: 379 -> tkn_id: 380 claimers[0x73c18BEeF34332e91E94250781DcE0BA996c072b] = 381; // seq: 380 -> tkn_id: 381 claimers[0x5451C07DEb2bc853081716632c7827e84bd2e24A] = 382; // seq: 381 -> tkn_id: 382 claimers[0x47dab6E0FEA8f3664b201EBEA2700458C25C66cc] = 383; // seq: 382 -> tkn_id: 383 claimers[0x3dE345e0042cBBDa5e1080691d9439DC1A35933e] = 384; // seq: 383 -> tkn_id: 384 claimers[0xb8AB7c24f5C52Ed17f1f38Eb8286Bd1888D3D68e] = 385; // seq: 384 -> tkn_id: 385 claimers[0xd7201730Fd6d8769ca80c3a77905a397F8732e90] = 386; // seq: 385 -> tkn_id: 386 claimers[0x256b09f7Ae7d5fec8C8ac77184CA09F867BbBf4c] = 387; // seq: 386 -> tkn_id: 387 claimers[0xDaE5D2ceaC11c0a9F15f745e55744C108a5fb266] = 388; // seq: 387 -> tkn_id: 388 claimers[0x2A967A09304B8334BE70cF9D9E10469127E4303D] = 389; // seq: 388 -> tkn_id: 389 claimers[0xAA504202187c620EeB0B1434695b32a2eE24E043] = 390; // seq: 389 -> tkn_id: 390 claimers[0xA8231e126fB45EdFE070d72583774Ee3FE55EcD9] = 391; // seq: 390 -> tkn_id: 391 claimers[0x015b2738D14Da6d7775444E6Cf0b46E722F45aDD] = 392; // seq: 391 -> tkn_id: 392 claimers[0x56cbBaF7F1eB247c4F526fE3e2109f19e5f63994] = 393; // seq: 392 -> tkn_id: 393 claimers[0xA0f31bF73eD86ab881d6E8f5Ae2E4Ec9E81f04Fc] = 394; // seq: 393 -> tkn_id: 394 claimers[0x3A484fc4E7873Bd79D0B9B05ED6067A549eC9f49] = 395; // seq: 394 -> tkn_id: 395 claimers[0x184cfB6915daDb4536D397fEcfA4fD8A18823719] = 396; // seq: 395 -> tkn_id: 396 claimers[0xee86f2BAFC7e33EFDD5cf3970e33C361Cb7aDeD9] = 397; // seq: 396 -> tkn_id: 397 claimers[0x4D3c3E7F5EBae3aCBac78EfF2457a842Ab86577e] = 398; // seq: 397 -> tkn_id: 398 claimers[0xf459958a3e43A9d08e7ce4567cd6Bba37304642D] = 399; // seq: 398 -> tkn_id: 399 claimers[0xC1e4B49876c3D4b5F4DfbF635a31a7CAE738d8D4] = 400; // seq: 399 -> tkn_id: 400 claimers[0xc09e52C36BeFcF605a7f308824395753Bb5693CE] = 401; // seq: 400 -> tkn_id: 401 claimers[0xC383395EdCf07183c5190833859751836755E549] = 402; // seq: 401 -> tkn_id: 402 claimers[0x41D43f1fb956351F39925C17b6639DFe198c6E58] = 403; // seq: 402 -> tkn_id: 403 claimers[0xea52Fb67C64EE535e6493bDA464c1776B029E68a] = 404; // seq: 403 -> tkn_id: 404 claimers[0x769Fcbe8A35D6B2E30cbD16B32CA6BA7D124FA5c] = 405; // seq: 404 -> tkn_id: 405 claimers[0x2733Deb98cC52921701A1FA018Bc084E017D6C2B] = 406; // seq: 405 -> tkn_id: 406 claimers[0xFB81414570E338E28C98417c38A3A5c9C6503516] = 407; // seq: 406 -> tkn_id: 407 claimers[0x0bEb916792e88Bc018a60403c2A5B3E88bc94E8C] = 408; // seq: 407 -> tkn_id: 408 claimers[0xC9A9943A2230ae6b3423F00d1435f96950f82B23] = 409; // seq: 408 -> tkn_id: 409 claimers[0x65028EEE0F81E76A8Ffc39721eD4c18643cB9A4C] = 410; // seq: 409 -> tkn_id: 410 claimers[0x0e173d5df309000cA6bC3a48064b6dA90642C088] = 411; // seq: 410 -> tkn_id: 411 claimers[0x5dB10F169d7193cb5A9A1A787b06E973e0c670eA] = 412; // seq: 411 -> tkn_id: 412 claimers[0xa6eB69bCA906F5A463E4BEdaf98cFb6eF4AeAF5f] = 413; // seq: 412 -> tkn_id: 413 claimers[0x053AA35E51A8Ef8F43fd0d89dd24Ef40a8C91556] = 414; // seq: 413 -> tkn_id: 414 claimers[0x90DB49Ac2f9d9ae14E9adBB4666bBbc890495fb3] = 415; // seq: 414 -> tkn_id: 415 claimers[0xaF85Cf9A8a0AfAE6071aaBe8856f487C1790Ef32] = 416; // seq: 415 -> tkn_id: 416 claimers[0x1d69159798e83d8eB39842367869D52be5EeD87d] = 417; // seq: 416 -> tkn_id: 417 claimers[0xD0A5ce6b581AFF1813f4376eF50A155e952218D8] = 418; // seq: 417 -> tkn_id: 418 claimers[0x915af533bFC63D46ffD38A0589AF6d2f5AC86B23] = 419; // seq: 418 -> tkn_id: 419 claimers[0xe5abD6895aE353496E4b44E212085B91bCD3274A] = 420; // seq: 419 -> tkn_id: 420 claimers[0x14b0b438A346d8555148e3765Cc3E6FE911546D5] = 421; // seq: 420 -> tkn_id: 421 claimers[0xAa7708065610BeEFB8e1aead8E27510bf5d5C3A8] = 422; // seq: 421 -> tkn_id: 422 claimers[0x2800D157C4D77F234AC49f401076BBf79fef6fF3] = 423; // seq: 422 -> tkn_id: 423 claimers[0xF33782f1384a931A3e66650c3741FCC279a838fC] = 424; // seq: 423 -> tkn_id: 424 claimers[0x20B5db733532A6a36B41BFE62bD177B6FA9622e7] = 425; // seq: 424 -> tkn_id: 425 claimers[0xa086F516d4591c0D2c67d9ABcbfee0D598eB3988] = 426; // seq: 425 -> tkn_id: 426 claimers[0x572AD2e517CBC0E7EA60948DfF099Fafde9d8022] = 427; // seq: 426 -> tkn_id: 427 claimers[0xbE3164647cfF2518931454DD55FD2bA0C7B29297] = 428; // seq: 427 -> tkn_id: 428 claimers[0x239D5c0CfD4ED667ad78Cdc7F3DCB17D09740a0d] = 429; // seq: 428 -> tkn_id: 429 claimers[0xdAD3f7d6D9Fa998c804b0BD7Cc02FA0C243bEE17] = 430; // seq: 429 -> tkn_id: 430 claimers[0x96C7fcC0d3426714Bf62c4B508A0fBADb7A9B692] = 431; // seq: 430 -> tkn_id: 431 claimers[0x2c46bc2F0b73b75248567CA25db6CA83d56dEA65] = 432; // seq: 431 -> tkn_id: 432 claimers[0x2220d8b0539CB4613A5112856a9B192b380be37f] = 433; // seq: 432 -> tkn_id: 433 claimers[0xcC3ee4f6002B17E741f6d753Da3DBB0c0EFbbC0F] = 434; // seq: 433 -> tkn_id: 434 claimers[0x6E9B220B915b6E18A1C36B6B7bcc5bde9838142B] = 435; // seq: 434 -> tkn_id: 435 claimers[0x3d370054667010D228822b60eA8e92A6491c6f13] = 436; // seq: 435 -> tkn_id: 436 claimers[0xd63613F91a6EFF9f479e052dF2c610108FE48048] = 437; // seq: 436 -> tkn_id: 437 claimers[0x0be82Fe1422d6D5cA74fd73A37a6C89636235B25] = 438; // seq: 437 -> tkn_id: 438 claimers[0xfA79F7c2601a4C2A40C80eC10cE0667988B0FC36] = 439; // seq: 438 -> tkn_id: 439 claimers[0x3786F2693B144d14b205B7CD719c71A95ffB8F82] = 440; // seq: 439 -> tkn_id: 440 claimers[0x88D09b28739B6C301be94b76Aab0554bde287D50] = 441; // seq: 440 -> tkn_id: 441 claimers[0xbdB1aD55728Be046C4eb3C24406c60fA8EB40A4F] = 442; // seq: 441 -> tkn_id: 442 claimers[0xF77bC2475ad7D0830753C87C375Fe9dF443dD1f5] = 443; // seq: 442 -> tkn_id: 443 claimers[0x0667b277d3CC7F8e0dc0c2106bD546214dB7B4B7] = 444; // seq: 443 -> tkn_id: 444 claimers[0x87698583DB020081DA64713E7A75D6276F970Ea6] = 445; // seq: 444 -> tkn_id: 445 claimers[0x49CEC0c4ec7B40e10aD2c46E4c863Fff9f0F8D09] = 446; // seq: 445 -> tkn_id: 446 claimers[0xAfc6bcc856644AA00A2e076e2EdDbA607326c517] = 447; // seq: 446 -> tkn_id: 447 claimers[0x8D8d7315f31C04c96E5c3944eE332599C3533131] = 448; // seq: 447 -> tkn_id: 448 claimers[0xc65D945aaAB7D2928A0bd9a51602451BD24E17cb] = 449; // seq: 448 -> tkn_id: 449 claimers[0x3A79caC51e770a84E8Cb5155AAafAA9CaC83F429] = 450; // seq: 449 -> tkn_id: 450 claimers[0x2b2248E158Bfe5710b82404b6Af9ceD5aE90b859] = 451; // seq: 450 -> tkn_id: 451 claimers[0x9c3C4d995BF0Cea85edF50ec552D1eEb879e1a47] = 452; // seq: 451 -> tkn_id: 452 claimers[0x93C927A836bF0CD6f92760ECB05E46A67D8A3FB3] = 453; // seq: 452 -> tkn_id: 453 claimers[0xaa8404c21A938551aD09719392a0Ed282538305F] = 454; // seq: 453 -> tkn_id: 454 claimers[0x03bE7e943c99eaF1630033adf8A9B8DE68e25D6E] = 455; // seq: 454 -> tkn_id: 455 claimers[0x2a8D7c661828c4e312Cde8e2CD8Ab63a1aCAD396] = 456; // seq: 455 -> tkn_id: 456 claimers[0xBeB6Bdb317bf0D7a3b3dA1D39bD07313b35c983f] = 457; // seq: 456 -> tkn_id: 457 claimers[0xf1180102846D1b587cD326358Bc1D54fC7441ec3] = 458; // seq: 457 -> tkn_id: 458 claimers[0x931ddC55Ea7074a190ded7429E82dfAdFeDC0269] = 459; // seq: 458 -> tkn_id: 459 claimers[0x871cAEF9d39e05f76A3F6A3Bb7690168f0188925] = 460; // seq: 459 -> tkn_id: 460 claimers[0x131BA338c35b0954Fd483C527852828B378666Db] = 461; // seq: 460 -> tkn_id: 461 claimers[0xADeA561251c72328EDf558CB0eBE536ae864fD74] = 462; // seq: 461 -> tkn_id: 462 claimers[0xdCB7Bf063D73FA67c987f459D885b3Df86061548] = 463; // seq: 462 -> tkn_id: 463 claimers[0xDaac8766ef95E86D839768F7EFf7ed972CA30628] = 464; // seq: 463 -> tkn_id: 464 claimers[0x07F3813CB3A7302eF49903f112e9543D44170a50] = 465; // seq: 464 -> tkn_id: 465 claimers[0x55E9762e2aa135584969DCd6A7d550A0FaadBcd6] = 466; // seq: 465 -> tkn_id: 466 claimers[0xca0d901CF1dddf950431849B2F200524C12baC1D] = 467; // seq: 466 -> tkn_id: 467 claimers[0x315a99D2403C2bdb04265ce74Ca375b513C7f0a4] = 468; // seq: 467 -> tkn_id: 468 claimers[0x05BE7F4a524a7169F66348d3A71CFc49654961EB] = 469; // seq: 468 -> tkn_id: 469 claimers[0x8D88F01D183DDfD30782E565fdBcD85c14413cAF] = 470; // seq: 469 -> tkn_id: 470 claimers[0xFb4ad2136d64C83762D9AcbAb12837ed0d47c1D4] = 471; // seq: 470 -> tkn_id: 471 claimers[0xD3Edeb449B2F93210D19e19A9E7f348998F437EC] = 472; // seq: 471 -> tkn_id: 472 claimers[0x9a1094393c60476FF2875E581c07CDbb51B8d63e] = 473; // seq: 472 -> tkn_id: 473 claimers[0x4F14B92dB4021d1545d396ba529c02464C692044] = 474; // seq: 473 -> tkn_id: 474 claimers[0xbb8b593aE36FaDFE56c20A054Bc095DFCcd000Ec] = 475; // seq: 474 -> tkn_id: 475 claimers[0xC0FFd04728F3D0Dd3d355d1DdE4F65740565A640] = 476; // seq: 475 -> tkn_id: 476 claimers[0x236D33B5CdBC9b44Ab2C5B0D3B43B3C365f7f455] = 477; // seq: 476 -> tkn_id: 477 claimers[0x31981027E99D7322bbfAAdC056e26c908b1A4eAf] = 478; // seq: 477 -> tkn_id: 478 claimers[0xa7A2FeB7fe3414832fc8DC0f55dcd66F04536C56] = 479; // seq: 478 -> tkn_id: 479 claimers[0x68E9496F98652a2FcFcA5a81B44A03D177567844] = 480; // seq: 479 -> tkn_id: 480 claimers[0x21130c9b9D00BcB6cDAF24d0E85809cf96251F35] = 481; // seq: 480 -> tkn_id: 481 claimers[0x0Ab49FcBdcf3D8d369D0C9E7Cd620e668c98C296] = 482; // seq: 481 -> tkn_id: 482 claimers[0x811Fc30D7eD89438E2FFad5df1Bd8F7560F41a37] = 483; // seq: 482 -> tkn_id: 483 claimers[0xb62C16D2D70B0121697Ed4ca4D5BAbeb5d573f8e] = 484; // seq: 483 -> tkn_id: 484 claimers[0x5E0bD50345356FdD6f3bDB7398D80e027975Ddf3] = 485; // seq: 484 -> tkn_id: 485 claimers[0x0118838575Be097D0e41E666924cd5E267ceF444] = 486; // seq: 485 -> tkn_id: 486 claimers[0x044D9739cAC0eE9aCB33D83a949ec7A4Ba342de4] = 487; // seq: 486 -> tkn_id: 487 claimers[0x3d8D1C9A6Db0C49774f28fE2E81C0083032522Be] = 488; // seq: 487 -> tkn_id: 488 claimers[0xCB95dC3DF3007330A5C6Ea57a7fBD0024F3560C0] = 489; // seq: 488 -> tkn_id: 489 claimers[0xcafEfe36aDE7561bb28037Ac8807AA4a5b22102e] = 490; // seq: 489 -> tkn_id: 490 claimers[0x2230A3fa220B0234E468a52389272d239CEB809d] = 491; // seq: 490 -> tkn_id: 491 claimers[0xA504BcF03748740b49dDA8b26BF3081D9dcd3114] = 492; // seq: 491 -> tkn_id: 492 claimers[0x357494619Aa4419437D10970E9F953c26C1aF51d] = 493; // seq: 492 -> tkn_id: 493 claimers[0x57AAeAB03d27B0EF9Dd45c79F3dd486b912e4Ed9] = 494; // seq: 493 -> tkn_id: 494 claimers[0x0753B66aA5652bA60F1b33C34Ee1E9bD85E0dC88] = 495; // seq: 494 -> tkn_id: 495 claimers[0xbbd85FE0869340D1458d593fF8379aed857C00aC] = 496; // seq: 495 -> tkn_id: 496 claimers[0x84c51a0237Bda0b4b0F820e03DB70a035e26Dd15] = 497; // seq: 496 -> tkn_id: 497 claimers[0x22827dF138Fb40F2A80c00245aF2177b5eB71F38] = 498; // seq: 497 -> tkn_id: 498 claimers[0x0Acc621E4956d1102DE13F1D8ED9B80dC98b8F5f] = 499; // seq: 498 -> tkn_id: 499 claimers[0xff8994c6a99a44b708dEA64897De7E4DD0Fb3939] = 500; // seq: 499 -> tkn_id: 500 claimers[0x2a0948cfFe88e193F453084A8702b59D8FeC6D5a] = 501; // seq: 500 -> tkn_id: 501 claimers[0x5a90f33f31924f0b502602C7f6a00F43EAaB7C0A] = 502; // seq: 501 -> tkn_id: 502 claimers[0x66251D264ED22E4eD362EA0FBDc3D96028786e85] = 503; // seq: 502 -> tkn_id: 503 claimers[0x76B8AeCDaC440a1f3bf300DE29bd0A652B67a94F] = 504; // seq: 503 -> tkn_id: 504 claimers[0x0534Ce5CbB832140d3B6a372217eEA65c4d8A65c] = 505; // seq: 504 -> tkn_id: 505 claimers[0x59897640bBF64426747BDf14bA4B9509c7404f77] = 506; // seq: 505 -> tkn_id: 506 claimers[0x7ACB9314364c7Fe3b01bc6B41E95eF3D360456d9] = 507; // seq: 506 -> tkn_id: 507 claimers[0xd2f97ADbe4bF3eaB86cA464c8C652977Ec72E51f] = 508; // seq: 507 -> tkn_id: 508 claimers[0xEc8c50223E785C3Ff21fd9F9ABafAcfB1e2215FC] = 509; // seq: 508 -> tkn_id: 509 claimers[0x843E8e7996F10d397b7C8b6251A035518D10D437] = 510; // seq: 509 -> tkn_id: 510 claimers[0x190f7a8e33E07d1230FA8C42bea1392606D02808] = 511; // seq: 510 -> tkn_id: 511 claimers[0x5c33ed519972c7cD746D261dcbBDa8ee6F9aadA7] = 512; // seq: 511 -> tkn_id: 512 claimers[0x1A33aC98AB15Ed89147Fe0edd5B726565d7972c9] = 513; // seq: 512 -> tkn_id: 513 claimers[0x915855E0b041468A8497c2E1D0959780904dA171] = 514; // seq: 513 -> tkn_id: 514 claimers[0x2Ee0781c7CE1f1BDe71fD2010F06448420873e58] = 515; // seq: 514 -> tkn_id: 515 claimers[0xC8ab8461129fEaE84c4aB3929948235106514AdF] = 516; // seq: 515 -> tkn_id: 516 claimers[0x75daA09CE22eD9e4e27cB1f2D0251647831642A6] = 517; // seq: 516 -> tkn_id: 517 claimers[0xA31D7fe5acCBBA9795b4B2f8c1b58abE90590D6d] = 518; // seq: 517 -> tkn_id: 518 claimers[0x85d03E980A35517906a3665866E8a255C0212918] = 519; // seq: 518 -> tkn_id: 519 claimers[0x02A325603C41c24E1897C74840B5C78950223366] = 520; // seq: 519 -> tkn_id: 520 claimers[0xF2CA16da81687313AE2d8d3DD122ABEF11e1f68f] = 521; // seq: 520 -> tkn_id: 521 claimers[0xba028A2a6097f7Da63866965B7f045F166aeB958] = 522; // seq: 521 -> tkn_id: 522 claimers[0x787Efe41F4C940bC8c2a0D2B1877B7Fb71bC7c04] = 523; // seq: 522 -> tkn_id: 523 claimers[0xA368bae3df1107cF22Daf0a79761EF94656D789A] = 524; // seq: 523 -> tkn_id: 524 claimers[0x67ffa298DD79AE9de27Fd63e99c15716ddc93491] = 525; // seq: 524 -> tkn_id: 525 claimers[0xD79B70C1D4Ab78Cd97d53508b5CBf0D573728980] = 526; // seq: 525 -> tkn_id: 526 claimers[0x8aA79517903E473c548A36d80f54b7669056249a] = 527; // seq: 526 -> tkn_id: 527 claimers[0xaEC4a7621BEA9F03B9A893d61e6e6EA91b33c395] = 528; // seq: 527 -> tkn_id: 528 claimers[0xF6614172a85D7cB91327bd11e4884d3C76042580] = 529; // seq: 528 -> tkn_id: 529 claimers[0x8F1B34eAF577413db89889beecdb61f4cc590aC2] = 530; // seq: 529 -> tkn_id: 530 claimers[0xD85bc15495DEa1C510fE41794d0ca7818d8558f0] = 531; // seq: 530 -> tkn_id: 531 claimers[0x85b931A32a0725Be14285B66f1a22178c672d69B] = 532; // seq: 531 -> tkn_id: 532 claimers[0xCDCaDF2195c1376f59808028eA21630B361Ba9b8] = 533; // seq: 532 -> tkn_id: 533 claimers[0x32527CA6ec2B85AbaCA0fb2dd3878e5b7Bb5b370] = 534; // seq: 533 -> tkn_id: 534 claimers[0xe3fa3aefD1f122e2228fFE79EE36685215A05BCa] = 535; // seq: 534 -> tkn_id: 535 claimers[0x7AE29F334D7cb67b58df5aE2A19F360F1Fd3bE75] = 536; // seq: 535 -> tkn_id: 536 claimers[0xF29919b09037036b6f10aD7C41ADCE8677BE2F54] = 537; // seq: 536 -> tkn_id: 537 claimers[0x328824B1468f47163787d0Fa40c44a04aaaF4fD9] = 538; // seq: 537 -> tkn_id: 538 claimers[0x4d4180739775105c82627CCbf043d6d32e746dee] = 539; // seq: 538 -> tkn_id: 539 claimers[0x6372b52593537A3Be2F3752110cb709e6f213241] = 540; // seq: 539 -> tkn_id: 540 claimers[0x75187bA60caFC4A2Cb057aADdD5c9FdAc3896Cee] = 541; // seq: 540 -> tkn_id: 541 claimers[0xf5503988423F65b1d5F2263d33Ab161E889103EB] = 542; // seq: 541 -> tkn_id: 542 claimers[0x76b2e65407e9f24cE944B62DB0c82e4b61850233] = 543; // seq: 542 -> tkn_id: 543 claimers[0xDd6177ba0f8C5F15DB178452585BB52A7b0C9Aee] = 544; // seq: 543 -> tkn_id: 544 claimers[0x3017dC24849823c81c43b6F8288bC85D6214FD7E] = 545; // seq: 544 -> tkn_id: 545 claimers[0xdf59a1d81880bDE9175c3B766c3e95bEd21c3670] = 546; // seq: 545 -> tkn_id: 546 claimers[0x2A716b58127BC4341231833E3A586582b07bBB22] = 547; // seq: 546 -> tkn_id: 547 claimers[0x15c5F3a14d4492b1a26f4c6557251a6F247a2Dd5] = 548; // seq: 547 -> tkn_id: 548 claimers[0x239af5a76A69de3F13aed6970fdF37bf86e8FEB7] = 549; // seq: 548 -> tkn_id: 549 claimers[0xCF6E7e0676f5AC61446F6865e26a0f34bb86A622] = 550; // seq: 549 -> tkn_id: 550 claimers[0xfb580744F1fDc4fEb83D9846E907a63Aa94979bd] = 551; // seq: 550 -> tkn_id: 551 claimers[0x3de1820D8d3B7f6C61C34dfD74F941c88cb27143] = 552; // seq: 551 -> tkn_id: 552 claimers[0xDFfF9Df5665BD156ECc71769103C72D8D167E30b] = 553; // seq: 552 -> tkn_id: 553 claimers[0xf4775496624C382f74aDbAE79C5780F353B1f83B] = 554; // seq: 553 -> tkn_id: 554 claimers[0xd1f157e1798D20F905e8391e3AcC2351bd9873Ff] = 555; // seq: 554 -> tkn_id: 555 claimers[0x2BcfEC37A16eb258d641812A308edEc5B80b32C1] = 556; // seq: 555 -> tkn_id: 556 claimers[0xD7CE5Cec413cC35edc293BD0e9D6204bEb91a470] = 557; // seq: 556 -> tkn_id: 557 claimers[0xC195a064BE7Ac37702Cd8FBcE4d71b57111d559b] = 558; // seq: 557 -> tkn_id: 558 claimers[0xc148113F6508589538d65B29426331A12B04bC6C] = 559; // seq: 558 -> tkn_id: 559 claimers[0x687922176D1BbcBcdC295E121BcCaA45A1f40fCd] = 560; // seq: 559 -> tkn_id: 560 claimers[0xba5270bFd7245C37db5e9Bb5fC18A68b8cA622F8] = 561; // seq: 560 -> tkn_id: 561 claimers[0x2022e7E902DdF290B70AAF5FB5D777E7840Fc9D3] = 562; // seq: 561 -> tkn_id: 562 claimers[0x676be4D726F6e648cC41AcF71b3d099dC65242f3] = 563; // seq: 562 -> tkn_id: 563 claimers[0xCbBdE3eeb1005A8be374C0eeB9c02e0e33Ac4629] = 564; // seq: 563 -> tkn_id: 564 claimers[0xaf636e6585a1cD5CDD23A75d32cbd57e6D836dA6] = 565; // seq: 564 -> tkn_id: 565 claimers[0x7dE08dAb472F16F6713bD30B1B1BCd29FA7AC68c] = 566; // seq: 565 -> tkn_id: 566 claimers[0xc8fa8A80D241a06CB53d61Ceacce0d1a8715Bc2f] = 567; // seq: 566 -> tkn_id: 567 claimers[0xA661Ff505C9Be09C08341666bbB32c46a80Fe996] = 568; // seq: 567 -> tkn_id: 568 claimers[0x934Cc457EDC4b58b105188C3ECE78c7b2EE65d80] = 569; // seq: 568 -> tkn_id: 569 claimers[0xFF4a498B23f2E3aD0A5eBEd838F07F30Ab4dC800] = 570; // seq: 569 -> tkn_id: 570 claimers[0xf75b052036dB7d90D18C10C06d3535F0fc3A4b74] = 571; // seq: 570 -> tkn_id: 571 claimers[0x8f2a707153378551c450Ec28B29c72C0B97664FC] = 572; // seq: 571 -> tkn_id: 572 claimers[0x77167885E8393f1052A8cE8D5dfF2fF16c08f98d] = 573; // seq: 572 -> tkn_id: 573 claimers[0x186D482EB263492318Cd470f3e4C0cf7705b3963] = 574; // seq: 573 -> tkn_id: 574 claimers[0x0736C28bd6186Cc899F72aB3f68f542bC2479d90] = 575; // seq: 574 -> tkn_id: 575 claimers[0x5E6DbCb38555ec7B4c5C12F19144736010335d26] = 576; // seq: 575 -> tkn_id: 576 claimers[0xd85d3AcC28A235f9128938B99E26747dB0ba655D] = 577; // seq: 576 -> tkn_id: 577 claimers[0x812E1eeE6D76e2F3490a8C29C0CC9e38D71a1a4f] = 578; // seq: 577 -> tkn_id: 578 claimers[0x66D61B6BEb130197E8194B072215d9aE9b36e14d] = 579; // seq: 578 -> tkn_id: 579 claimers[0x36986961cc3037E40Ef6f01A7481941ed08aF566] = 580; // seq: 579 -> tkn_id: 580 claimers[0xB6ea652fBE96DeddC5fc7133C208D024f3CFFf5a] = 581; // seq: 580 -> tkn_id: 581 claimers[0x2F86c6e97C4E2d03939AfE7452448bD96b681938] = 582; // seq: 581 -> tkn_id: 582 claimers[0x6F36a7E4eA93aCbF753397C96DaBacD45ba88175] = 583; // seq: 582 -> tkn_id: 583 claimers[0x6394e38E5Fe6Fb9de9B2dD267F257035fe72a315] = 584; // seq: 583 -> tkn_id: 584 claimers[0xeE74a1e81B6C55e3D02D05D7CaE9FD6BCee0E651] = 585; // seq: 584 -> tkn_id: 585 claimers[0x9A7797Cf292579065CC204C5c975E0E7E9dF66f7] = 586; // seq: 585 -> tkn_id: 586 claimers[0xf50E61952aC37fa5DD770657326A5FBDB18cB694] = 587; // seq: 586 -> tkn_id: 587 claimers[0x0B60fF27655bCd5E9444c5D1865ec8CD3B403146] = 588; // seq: 587 -> tkn_id: 588 claimers[0x35f382D9daA602A23AD988D5bf837B8e6A01d002] = 589; // seq: 588 -> tkn_id: 589 claimers[0xFF7C32e9D881e6cabBCE7C0C17564F54260C3872] = 590; // seq: 589 -> tkn_id: 590 claimers[0xdE437ad59B5fcad477eB90a4742916FD04c0193e] = 591; // seq: 590 -> tkn_id: 591 claimers[0xB9f2946b6f35d8BB4a1522e7628F24416947ddda] = 592; // seq: 591 -> tkn_id: 592 claimers[0x67AE8A6e6587e6219141dC5a5BE35f30Beb30C50] = 593; // seq: 592 -> tkn_id: 593 claimers[0x04b5b1906745FE9E501C10B3191118FA76CD76Ba] = 594; // seq: 593 -> tkn_id: 594 claimers[0xc793B339FC99A912d8c4c420f55023e072Dc4A08] = 595; // seq: 594 -> tkn_id: 595 claimers[0x024713784f675dd28b5CE07dB91a4d47213c2394] = 596; // seq: 595 -> tkn_id: 596 claimers[0xE9011643a76aC1Ee4BDb32242B28424597C724A2] = 597; // seq: 596 -> tkn_id: 597 claimers[0xFA3ed3EDd606157c2FD49c900a0B1fE867b96d78] = 598; // seq: 597 -> tkn_id: 598 claimers[0xEb06301D471b0F8C8C5CC965B09Ce0B85021D398] = 599; // seq: 598 -> tkn_id: 599 claimers[0x57985E22ae7906cC693b44cC16473643F294Ff07] = 600; // seq: 599 -> tkn_id: 600 claimers[0x3ef7Bf350074EFDE3FD107ce38e652a10a5750f5] = 601; // seq: 600 -> tkn_id: 601 claimers[0xAA5990c918b845EE54ade1a962aDb9ddfF17D20A] = 602; // seq: 601 -> tkn_id: 602 claimers[0x7Ff698e124d1D14E6d836aF4dA0Ae448c8FfFa6F] = 603; // seq: 602 -> tkn_id: 603 claimers[0x95351210cf4F6270aaD413d5A2E07256a005D9B3] = 604; // seq: 603 -> tkn_id: 604 claimers[0x2aE024C5EE8dA720b9A51F50D53a291aca37dEb1] = 605; // seq: 604 -> tkn_id: 605 claimers[0xe0dAA80c1fF85fd070b561ef44cC7637059E5e57] = 606; // seq: 605 -> tkn_id: 606 claimers[0xD64212269c456D61bCA45403c4B93A2a57B7510E] = 607; // seq: 606 -> tkn_id: 607 claimers[0xC3A9eB254C875750A83750d1258220fA8a729F89] = 608; // seq: 607 -> tkn_id: 608 claimers[0x07b678695690183C644fEb37d9E95eBa4eFe53A8] = 609; // seq: 608 -> tkn_id: 609 claimers[0x4334c48D71b8D03799487a601509ac137b29904B] = 610; // seq: 609 -> tkn_id: 610 claimers[0xea2D190cBb3Be5074E9E144EDE095f059eDB7E53] = 611; // seq: 610 -> tkn_id: 611 claimers[0x93973b0dc20bEff165C087cB2A319640C210f30e] = 612; // seq: 611 -> tkn_id: 612 claimers[0x8015eA3DA10b9960378CdF6d529EBf19553c112A] = 613; // seq: 612 -> tkn_id: 613 claimers[0xE40Cc4De1a57e83AAc249Bb4EF833B766f26e2F2] = 614; // seq: 613 -> tkn_id: 614 claimers[0xdD2B93A4F52C138194C10686f175df55db690117] = 615; // seq: 614 -> tkn_id: 615 claimers[0x2EF48fA1785aE0C24fd791c1D7BAaf690d153793] = 616; // seq: 615 -> tkn_id: 616 claimers[0x2044E9cF4a61D4a49C73800168Ecfd8Bd19550c4] = 617; // seq: 616 -> tkn_id: 617 claimers[0xF6711aFF1462fd2f477769C2d442Cf2b10597C6D] = 618; // seq: 617 -> tkn_id: 618 claimers[0xf9F49E8B93f60535852A91FeE294fF6c4D460035] = 619; // seq: 618 -> tkn_id: 619 claimers[0x61b3c4c9dc16B686eD396319D48586f40c1F74E9] = 620; // seq: 619 -> tkn_id: 620 claimers[0x348F0cE2c24f14EfC18bfc2B2048726BDCDB759e] = 621; // seq: 620 -> tkn_id: 621 claimers[0x32f8E5d3F4039d1DF89B6A1e544288289A500Fd1] = 622; // seq: 621 -> tkn_id: 622 claimers[0xaF997affb94c5Ca556b28b024E162AA3164f4A43] = 623; // seq: 622 -> tkn_id: 623 claimers[0xb20Ce1911054DE1D77E1a66ec402fcB3d06c06c2] = 624; // seq: 623 -> tkn_id: 624 claimers[0xB83FC0c399e46b69e330f19baEB87B6832Ec890d] = 625; // seq: 624 -> tkn_id: 625 claimers[0x01B9b335Bb0D8Ff543f54eb9A59Ba57dBEf7A93B] = 626; // seq: 625 -> tkn_id: 626 claimers[0x2CC7dA5EF8fd01f4a7cD03E785A01941F28fE8da] = 627; // seq: 626 -> tkn_id: 627 claimers[0x46f75A3e9702d89E3E269361D9c1e4D2A9779044] = 628; // seq: 627 -> tkn_id: 628 claimers[0x7AEBDD84821190c1cfCaCe051E87913ae5d67439] = 629; // seq: 628 -> tkn_id: 629 claimers[0xE94F4519Ed1670123714d8f67B3A144Bf089f594] = 630; // seq: 629 -> tkn_id: 630 claimers[0xf10367decc6F0e6A12Aa14E7512AF94a4C791Fd7] = 631; // seq: 630 -> tkn_id: 631 claimers[0x49BA4256FE65b833b3dA9c26aA27E1eFD74EFD1d] = 632; // seq: 631 -> tkn_id: 632 claimers[0x33BE249B512DCb6D2FC7586047ab0220397aF2d3] = 633; // seq: 632 -> tkn_id: 633 claimers[0x07b449319D200b1189406c58967348c5bA0D4083] = 634; // seq: 633 -> tkn_id: 634 claimers[0x9B6498Ef7F47223f5F7d466FC4D26c570C7b375F] = 635; // seq: 634 -> tkn_id: 635 claimers[0xA40F625ce8e06Db1C41Bb7F8854C7d57644Ff9Cc] = 636; // seq: 635 -> tkn_id: 636 claimers[0x28864AF76e73B38e2C9D4e856Ea97F66947961aB] = 637; // seq: 636 -> tkn_id: 637 claimers[0x4aC4Ab29F4A87150D89D3fdd5cbC46112606E5e8] = 638; // seq: 637 -> tkn_id: 638 claimers[0x9D29BBF508cDf300D116FCA3cE3cd9d287850ccd] = 639; // seq: 638 -> tkn_id: 639 claimers[0xcC5Fb93A6e274Ac3C626a02B24F939b1307b46e1] = 640; // seq: 639 -> tkn_id: 640 claimers[0x0E590293aD7CB2Dd9968B7f16eac9614451A63E1] = 641; // seq: 640 -> tkn_id: 641 claimers[0x726d54570632b30c957E60CFf44AD4eE2b559dB6] = 642; // seq: 641 -> tkn_id: 642 claimers[0xE2927F7f6618E71A86CE3F8F5AC32B5BbFe163a6] = 643; // seq: 642 -> tkn_id: 643 claimers[0x3C7DEd16d0E5b5bA9fb3DE539ed28cb7B7D8C95C] = 644; // seq: 643 -> tkn_id: 644 claimers[0xB7c3A0928c06A80DC4A4CDc9dC0aec33E047A4c8] = 645; // seq: 644 -> tkn_id: 645 claimers[0x95f26898b144FF93283d38d0B1A92b69f90d3123] = 646; // seq: 645 -> tkn_id: 646 claimers[0x95a788A34b7781eF34660196BB615A97F7e7d2B8] = 647; // seq: 646 -> tkn_id: 647 claimers[0x317EA9Dd8fCac5A6Fd94eB2959FeC690931b61b8] = 648; // seq: 647 -> tkn_id: 648 claimers[0x2CE83785eD44961959bf5251e85af897Ba9ddAC7] = 649; // seq: 648 -> tkn_id: 649 claimers[0xE144E7e3948dCA4AD395794031A0289a83b150A0] = 650; // seq: 649 -> tkn_id: 650 claimers[0x18668B0244949570ec637465BAFdDe4d082afa69] = 651; // seq: 650 -> tkn_id: 651 claimers[0xaba035729057984c7431a711436D3e51e947cbD4] = 652; // seq: 651 -> tkn_id: 652 claimers[0x2519410f255A52CDF22a7DFA870073b1357B30A7] = 653; // seq: 652 -> tkn_id: 653 claimers[0x63a12D51Ee95eF213404308e1F8a2805A0c21899] = 654; // seq: 653 -> tkn_id: 654 claimers[0x882bBB07991c5c2f65988fd077CdDF405FE5b56f] = 655; // seq: 654 -> tkn_id: 655 claimers[0x11f53fdAb3054a5cA63778659263aF0838b642b1] = 656; // seq: 655 -> tkn_id: 656 claimers[0x093E088901909dEecC1b4a1479fBcCE1FBEd31E7] = 657; // seq: 656 -> tkn_id: 657 claimers[0x3c5cBddC5D6D6720d51CB563134d72E20dc4C713] = 658; // seq: 657 -> tkn_id: 658 claimers[0x3Db111A09A2e77A8DD6d03dc3f089f4A0F4557E9] = 659; // seq: 658 -> tkn_id: 659 claimers[0x8F53cA524c1451A930DEA18926df964Fb72B10F1] = 660; // seq: 659 -> tkn_id: 660 claimers[0x22C535D5EccCF398997eabA19Aa3FAbd3fe6AA16] = 661; // seq: 660 -> tkn_id: 661 claimers[0x93dF35071B3bc1B6d16D5f5F20fbB2be9D50FE67] = 662; // seq: 661 -> tkn_id: 662 claimers[0xfE61D830b99E40b3E905CD7EcF4a08DD06fa7F03] = 663; // seq: 662 -> tkn_id: 663 claimers[0x9cB5FAF0801ac959a0d40b2A7D69Ed8E42F792eA] = 664; // seq: 663 -> tkn_id: 664 claimers[0xC5B0f2afEC01807D964D76aEce6dB2F093239619] = 665; // seq: 664 -> tkn_id: 665 claimers[0x9b279dbaB2aE483EEDD106a583ACbBCFd722CE79] = 666; // seq: 665 -> tkn_id: 666 claimers[0x429c74f7C7fe7d31a70289e9B4b54e0F7300f376] = 667; // seq: 666 -> tkn_id: 667 claimers[0xeD08e8D72D35428b28390B7334ebe7F9f7a64822] = 668; // seq: 667 -> tkn_id: 668 claimers[0xB468076716C800Ce1eB9e9F515488099cC838128] = 669; // seq: 668 -> tkn_id: 669 claimers[0x3D7A35c89f04Af71F453b33848B49714859D061c] = 670; // seq: 669 -> tkn_id: 670 claimers[0x7DcE9e613b3583C600255A230497DD77429b0e21] = 671; // seq: 670 -> tkn_id: 671 claimers[0x2B00CaD253E88924290fFC7FeE221D135A0f083a] = 672; // seq: 671 -> tkn_id: 672 claimers[0xA2A64dE6BEe8c68DBCC948609708Ae54801CBAd8] = 673; // seq: 672 -> tkn_id: 673 claimers[0x6F255406306D6D78e97a29F7f249f6d2d85d9801] = 674; // seq: 673 -> tkn_id: 674 claimers[0xcDaf4c2e205A8077F29BF1dfF9Bd0B6a501B72cB] = 675; // seq: 674 -> tkn_id: 675 claimers[0xC45bF67A729B9A2b98521CDbCbf8bc70d8b81af3] = 676; // seq: 675 -> tkn_id: 676 claimers[0x35205135F0883e6a59aF9cb64310c53003433122] = 677; // seq: 676 -> tkn_id: 677 claimers[0xbAFcFC93A2fb6a042CA87f3d70670E2c114CE9fd] = 678; // seq: 677 -> tkn_id: 678 claimers[0xf664D1363FcE2da5ebb9aA935ef11Ce07be012Db] = 679; // seq: 678 -> tkn_id: 679 claimers[0x57e7ce99461FDeA80Ae8a6292e58AEfe053ed3a3] = 680; // seq: 679 -> tkn_id: 680 claimers[0xbD0Ad704f38AfebbCb4BA891389938D4177A8A92] = 681; // seq: 680 -> tkn_id: 681 claimers[0x0962FEeC7d4f0fa0EBadf6cd2e1CB783103B41F4] = 682; // seq: 681 -> tkn_id: 682 claimers[0x9B89f9Fd0952009fd556b19B18d85dA1089D005C] = 683; // seq: 682 -> tkn_id: 683 claimers[0xa511CB01cCe9c221cC73a9f9231937Cf6baf1D1A] = 684; // seq: 683 -> tkn_id: 684 claimers[0x79e5c907b9d4Af5840C687e6975a1C530895454a] = 685; // seq: 684 -> tkn_id: 685 claimers[0xf782f0Bf9B741FdE0E7c7dA4f71c7E33554f8397] = 686; // seq: 685 -> tkn_id: 686 claimers[0x228Bb6C83e8d0767eD342dd333DDbD55Ad217a3D] = 687; // seq: 686 -> tkn_id: 687 claimers[0xf2f62B5C7B3395b0ACe219d1B91D8083f8394720] = 688; // seq: 687 -> tkn_id: 688 claimers[0x2A77484F4cca78a5B3f71c22A50e3A1b8583072D] = 689; // seq: 688 -> tkn_id: 689 claimers[0xbB85877c4AEa11A141FC107Dc8D2E43C4B04F8C8] = 690; // seq: 689 -> tkn_id: 690 claimers[0x0414B2A60f8d4b84dE036677f8780F59AFEc1b65] = 691; // seq: 690 -> tkn_id: 691 claimers[0xb3aA296e046E0EFBd734cfa5DCd447Ae3a5e6104] = 692; // seq: 691 -> tkn_id: 692 claimers[0xa6700EA3f19830e2e8b35363c2978cb9D5630303] = 693; // seq: 692 -> tkn_id: 693 claimers[0xF976106afd7ADE91F8dFc5167284AD57795b17B1] = 694; // seq: 693 -> tkn_id: 694 claimers[0x793E446AFFf802e20bdb496A64250622BE32Df29] = 695; // seq: 694 -> tkn_id: 695 claimers[0x2E72d671fa07be54ae9671f793895520268eF00E] = 696; // seq: 695 -> tkn_id: 696 claimers[0xB67c99dfb3422b61f9E38070f021eaB7B42e9CAF] = 697; // seq: 696 -> tkn_id: 697 claimers[0x0095D1f7804D32A7921b26D3Eb1229873D3B11E0] = 698; // seq: 697 -> tkn_id: 698 claimers[0xEf31D013E222AaD9Eb90df9fd466c758B7603FaB] = 699; // seq: 698 -> tkn_id: 699 claimers[0x9936f05D5cE4259D44Aa51d54c0C245652efcc11] = 700; // seq: 699 -> tkn_id: 700 claimers[0x58bb897f0612235FA7Ae324F9b9718a06A2f6df3] = 701; // seq: 700 -> tkn_id: 701 claimers[0xa2cF94Bf60B6a6C08488B756E6695d990574e9C7] = 702; // seq: 701 -> tkn_id: 702 claimers[0x47754f6dCb011A308c91a666c5245abbC577c9eD] = 703; // seq: 702 -> tkn_id: 703 claimers[0xB6a95916221Abef28339594161cd154Bc650c515] = 704; // seq: 703 -> tkn_id: 704 claimers[0xb0471Ad0fEFD2151Efaa6C8415b1dB984526c0a6] = 705; // seq: 704 -> tkn_id: 705 claimers[0xC869ce145a5a72985540285Efde28f5176F39bC9] = 706; // seq: 705 -> tkn_id: 706 claimers[0x79440849d5BA6Df5fb1F45Ff36BE3979F4271fa4] = 707; // seq: 706 -> tkn_id: 707 claimers[0xD54F610d744b64393386a354cf1ADD944cBD42c9] = 708; // seq: 707 -> tkn_id: 708 claimers[0x3b368E77F110e3FE1C8482F395E51D1f75e50e5f] = 709; // seq: 708 -> tkn_id: 709 claimers[0x529ccAFA5aC0d18E7402244859AF8664BA736919] = 710; // seq: 709 -> tkn_id: 710 claimers[0x686241b898D7616FF78e22cc45fb07e92A74B7B5] = 711; // seq: 710 -> tkn_id: 711 claimers[0xd859ad8D8DCA1eEC61529833685FE59FAb804E7d] = 712; // seq: 711 -> tkn_id: 712 claimers[0x5AbfC4E2bB4941BD6773f120573618Ba8a4f7863] = 713; // seq: 712 -> tkn_id: 713 claimers[0x17c1cF2eeFda3f339996c67cd18d4389D132D033] = 714; // seq: 713 -> tkn_id: 714 claimers[0x6Ce5B05f0C6A8129DE3C7fC3E69ca35Be3ECB35e] = 715; // seq: 714 -> tkn_id: 715 claimers[0x4B992870CF27A548921082be7B447fc3c0534509] = 716; // seq: 715 -> tkn_id: 716 claimers[0xa278039DEE9B1fC58164Ef7B6f5eC86de9786178] = 717; // seq: 716 -> tkn_id: 717 claimers[0xBa64c61B45340994bABF676544025BcCc0bE6A9e] = 718; // seq: 717 -> tkn_id: 718 claimers[0x3656f4d852f15986beBE025AEF64a40dF2A5d4a1] = 719; // seq: 718 -> tkn_id: 719 claimers[0x4A57385D14882d6d8FDB3916792E9585102d22DA] = 720; // seq: 719 -> tkn_id: 720 claimers[0x764108BAcf10e30F6f249d17E7612fB9008923F0] = 721; // seq: 720 -> tkn_id: 721 claimers[0x880BD9ec1d3b71Bda5249baCCC63E9a8e5902250] = 722; // seq: 721 -> tkn_id: 722 claimers[0x1195e87Ca87C8f5989ecBa2d569E64784E5820f9] = 723; // seq: 722 -> tkn_id: 723 claimers[0x8591D21143794463A69017944F555E272965db06] = 724; // seq: 723 -> tkn_id: 724 claimers[0x032c255E5a84C2E8Ca242f85098988D69b982E85] = 725; // seq: 724 -> tkn_id: 725 claimers[0xFD9bCD1F71Cb016079077F659Ee99f8AD834732A] = 726; // seq: 725 -> tkn_id: 726 claimers[0x6Be049Bb4688dFf540E7798433c925E21c70Ac25] = 727; // seq: 726 -> tkn_id: 727 claimers[0xFbFB1aD08f5d60d0243CC88E1EDf9eD5875d2EFe] = 728; // seq: 727 -> tkn_id: 728 claimers[0xeBe91f187bF0b29185a8e4A362392Aa3665030a1] = 729; // seq: 728 -> tkn_id: 729 claimers[0xF6666FCE84FDe632f33c1A881b6AC2C0f545D271] = 730; // seq: 729 -> tkn_id: 730
seq: 274 -> tkn_id: 274
claimers[0x9e0eD477f110cb75453181Cd4261D40Fa7396056] = 274;
12,654,770
[ 1, 5436, 30, 576, 5608, 317, 13030, 82, 67, 350, 30, 576, 5608, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 14784, 414, 63, 20, 92, 29, 73, 20, 73, 40, 24, 4700, 74, 17506, 7358, 5877, 7950, 23, 2643, 21, 19728, 24, 5558, 21, 40, 7132, 29634, 27, 5520, 4848, 4313, 65, 273, 576, 5608, 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 ]
//Address: 0xE7c31C786c5CaB6F8cb2B9E03F6f534f8c3e8C3F //Contract name: ZMINE //Balance: 0 Ether //Verification Date: 12/21/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Authorizable * @dev The Authorizable contract has authorized addresses, and provides basic authorization control * functions, this simplifies the implementation of "multiple user permissions". */ contract Authorizable is Ownable { mapping(address => bool) public authorized; event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization); /** * @dev The Authorizable constructor sets the first `authorized` of the contract to the sender * account. */ function Authorizable() public { AuthorizationSet(msg.sender, true); authorized[msg.sender] = true; } /** * @dev Throws if called by any account other than the authorized. */ modifier onlyAuthorized() { require(authorized[msg.sender]); _; } /** * @dev Allows the current owner to set an authorization. * @param addressAuthorized The address to change authorization. */ function setAuthorized(address addressAuthorized, bool authorization) public onlyOwner { require(authorized[addressAuthorized] != authorization); AuthorizationSet(addressAuthorized, authorization); authorized[addressAuthorized] = authorization; } } /** * @title WhiteList * @dev The WhiteList contract has whiteListed addresses, and provides basic whiteListStatus control * functions, this simplifies the implementation of "multiple user permissions". */ contract WhiteList is Authorizable { mapping(address => bool) whiteListed; event WhiteListSet(address indexed addressWhiteListed, bool indexed whiteListStatus); /** * @dev The WhiteList constructor sets the first `whiteListed` of the contract to the sender * account. */ function WhiteList() public { WhiteListSet(msg.sender, true); whiteListed[msg.sender] = true; } /** * @dev Throws if called by any account other than the whiteListed. */ modifier onlyWhiteListed() { require(whiteListed[msg.sender]); _; } function isWhiteListed(address _address) public view returns (bool) { return whiteListed[_address]; } /** * @dev Allows the current owner to set an whiteListStatus. * @param addressWhiteListed The address to change whiteListStatus. */ function setWhiteListed(address addressWhiteListed, bool whiteListStatus) public onlyAuthorized { require(whiteListed[addressWhiteListed] != whiteListStatus); WhiteListSet(addressWhiteListed, whiteListStatus); whiteListed[addressWhiteListed] = whiteListStatus; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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 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]; } } /** * @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 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; } } contract TreasureBox { // ERC20 basic token contract being held StandardToken token; // beneficiary of tokens after they are released address public beneficiary; // timestamp where token release is enabled uint public releaseTime; function TreasureBox(StandardToken _token, address _beneficiary, uint _releaseTime) public { require(_beneficiary != address(0)); token = StandardToken(_token); beneficiary = _beneficiary; releaseTime = _releaseTime; } function claim() external { require(available()); require(amount() > 0); token.transfer(beneficiary, amount()); } function available() public view returns (bool) { return (now >= releaseTime); } function amount() public view returns (uint256) { return token.balanceOf(this); } } contract AirDropper is Authorizable { mapping(address => bool) public isAnExchanger; // allow to airdrop to destination is exchanger with out minimum mapping(address => bool) public isTreasureBox; // flag who not eligible airdrop mapping(address => address) public airDropDestinations; // setTo 0x0 if want airdrop to self StandardToken token; event SetDestination(address _address, address _destination); event SetExchanger(address _address, bool _isExchanger); function AirDropper(StandardToken _token) public { token = _token; } function getToken() public view returns(StandardToken) { return token; } /** * set _destination to 0x0 if want to self airdrop */ function setAirDropDestination(address _destination) external { require(_destination != msg.sender); airDropDestinations[msg.sender] = _destination; SetDestination(msg.sender, _destination); } function setTreasureBox (address _address, bool _status) public onlyAuthorized { require(_address != address(0)); require(isTreasureBox[_address] != _status); isTreasureBox[_address] = _status; } function setExchanger(address _address, bool _isExchanger) external onlyAuthorized { require(_address != address(0)); require(isAnExchanger[_address] != _isExchanger); isAnExchanger[_address] = _isExchanger; SetExchanger(_address, _isExchanger); } /** * help fix airdrop when holder > 100 * but need to calculate outer */ function multiTransfer(address[] _address, uint[] _value) public returns (bool) { for (uint i = 0; i < _address.length; i++) { token.transferFrom(msg.sender, _address[i], _value[i]); } return true; } } /** * @title TemToken * @dev The main ZMINE token contract * * ABI * [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"startTrading","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"tradingStarted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}] */ contract ZMINE is StandardToken, Ownable { string public name = "ZMINE Token"; string public symbol = "ZMN"; uint8 public decimals = 18; uint256 public totalSupply = 1000000000000000000000000000; // 1,000,000,000 ^ 18 function ZMINE() public { balances[owner] = totalSupply; Transfer(address(0x0), owner, totalSupply); } /** * burn token if token is not sold out after Public */ function burn(uint _amount) external onlyOwner { require(balances[owner] >= _amount); balances[owner] = balances[owner] - _amount; totalSupply = totalSupply - _amount; Transfer(owner, address(0x0), _amount); } } contract RateContract is Authorizable { uint public rate = 6000000000000000000000; event UpdateRate(uint _oldRate, uint _newRate); function updateRate(uint _rate) public onlyAuthorized { require(rate != _rate); UpdateRate(rate, _rate); rate = _rate; } function getRate() public view returns (uint) { return rate; } } contract FounderThreader is Ownable { using SafeMath for uint; event TokenTransferForFounder(address _recipient, uint _value, address box1, address box2); AirDropper public airdropper; uint public hardCap = 300000000000000000000000000; // 300 000 000 * 1e18 uint public remain = 300000000000000000000000000; // 300 000 000 * 1e18 uint public minTx = 100000000000000000000; // 100 * 1e18 mapping(address => bool) isFounder; function FounderThreader (AirDropper _airdropper, address[] _founders) public { airdropper = AirDropper(_airdropper); for (uint i = 0; i < _founders.length; i++) { isFounder[_founders[i]] = true; } } function transferFor(address _recipient, uint _tokens) external onlyOwner { require(_recipient != address(0)); require(_tokens >= minTx); require(isFounder[_recipient]); StandardToken token = StandardToken(airdropper.getToken()); TreasureBox box1 = new TreasureBox(token, _recipient, 1533088800); // can open 2018-08-01 09+07:00 TreasureBox box2 = new TreasureBox(token, _recipient, 1548986400); // can open 2019-02-01 09+07:00 airdropper.setTreasureBox(box1, true); airdropper.setTreasureBox(box2, true); token.transferFrom(owner, _recipient, _tokens.mul(33).div(100)); // 33 % for now token.transferFrom(owner, box1, _tokens.mul(33).div(100)); // 33 % for box1 token.transferFrom(owner, box2, _tokens.mul(34).div(100)); // 34 % for box2 remain = remain.sub(_tokens); TokenTransferForFounder(_recipient, _tokens, box1, box2); } } contract PreSale is Ownable { using SafeMath for uint; event TokenSold(address _recipient, uint _value, uint _tokens, uint _rate); event TokenSold(address _recipient, uint _tokens); ZMINE public token; WhiteList whitelist; uint public hardCap = 300000000000000000000000000; // 300 000 000 * 1e18 uint public remain = 300000000000000000000000000; // 300 000 000 * 1e18 uint public startDate = 1512525600; // 2017-12-06 09+07:00 uint public stopDate = 1517364000; // 2018-01-31 09+07:00 uint public minTx = 100000000000000000000; // 100 * 1e18 uint public maxTx = 100000000000000000000000; // 100 000 * 1e18 RateContract rateContract; function PreSale (ZMINE _token, RateContract _rateContract, WhiteList _whitelist) public { token = ZMINE(_token); rateContract = RateContract(_rateContract); whitelist = WhiteList(_whitelist); } /** * transfer token to presale investor who pay by cash */ function transferFor(address _recipient, uint _tokens) external onlyOwner { require(_recipient != address(0)); require(available()); remain = remain.sub(_tokens); token.transferFrom(owner, _recipient, _tokens); TokenSold(_recipient, _tokens); } function sale(address _recipient, uint _value, uint _rate) private { require(_recipient != address(0)); require(available()); require(isWhiteListed(_recipient)); require(_value >= minTx && _value <= maxTx); uint tokens = _rate.mul(_value).div(1000000000000000000); remain = remain.sub(tokens); token.transferFrom(owner, _recipient, tokens); owner.transfer(_value); TokenSold(_recipient, _value, tokens, _rate); } function rate() public view returns (uint) { return rateContract.getRate(); } function available() public view returns (bool) { return (now > startDate && now < stopDate); } function isWhiteListed(address _address) public view returns (bool) { return whitelist.isWhiteListed(_address); } function() external payable { sale(msg.sender, msg.value, rate()); } } contract PublicSale is Ownable { using SafeMath for uint; event TokenSold(address _recipient, uint _value, uint _tokens, uint _rate); event IncreaseHardCap(uint _amount); ZMINE public token; WhiteList whitelistPublic; WhiteList whitelistPRE; uint public hardCap = 400000000000000000000000000; // 400 000 000 * 1e18 uint public remain = 400000000000000000000000000; // 400 000 000 * 1e18 uint public startDate = 1515376800; // 2018-01-08 09+07:00 uint public stopDate = 1517364000; // 2018-01-31 09+07:00 uint public minTx = 1000000000000000000; // 1e18 uint public maxTx = 100000000000000000000000; // 100 000 1e18 RateContract rateContract; function PublicSale(ZMINE _token, RateContract _rateContract, WhiteList _whitelistPRE, WhiteList _whitelistPublic) public { token = ZMINE(_token); rateContract = RateContract(_rateContract); whitelistPRE = WhiteList(_whitelistPRE); whitelistPublic = WhiteList(_whitelistPublic); } /** * increase hard cap if previous dont sold out */ function increaseHardCap(uint _amount) external onlyOwner { require(_amount <= 300000000000000000000000000); // presale hard cap hardCap = hardCap.add(_amount); remain = remain.add(_amount); IncreaseHardCap(_amount); } function sale(address _recipient, uint _value, uint _rate) private { require(available()); require(isWhiteListed(_recipient)); require(_value >= minTx && _value <= maxTx); uint tokens = _rate.mul(_value).div(1000000000000000000); remain = remain.sub(tokens); token.transferFrom(owner, _recipient, tokens); owner.transfer(_value); TokenSold(_recipient, _value, tokens, _rate); } function rate() public view returns (uint) { return rateContract.getRate(); } function available () public view returns (bool) { return (now > startDate && now < stopDate); } function isWhiteListed (address _address) public view returns(bool) { return (whitelistPRE.isWhiteListed(_address) || (whitelistPublic.isWhiteListed(_address))); } function() external payable { sale(msg.sender, msg.value, rate()); } }
* transfer token to presale investor who pay by cash/
function transferFor(address _recipient, uint _tokens) external onlyOwner { require(_recipient != address(0)); require(available()); remain = remain.sub(_tokens); token.transferFrom(owner, _recipient, _tokens); TokenSold(_recipient, _tokens); }
1,022,423
[ 1, 13866, 1147, 358, 4075, 5349, 2198, 395, 280, 10354, 8843, 635, 276, 961, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1290, 12, 2867, 389, 20367, 16, 2254, 389, 7860, 13, 3903, 1338, 5541, 288, 203, 565, 2583, 24899, 20367, 480, 1758, 12, 20, 10019, 203, 565, 2583, 12, 5699, 10663, 203, 203, 565, 7232, 273, 7232, 18, 1717, 24899, 7860, 1769, 203, 565, 1147, 18, 13866, 1265, 12, 8443, 16, 389, 20367, 16, 389, 7860, 1769, 203, 203, 565, 3155, 55, 1673, 24899, 20367, 16, 389, 7860, 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 ]
./full_match/4/0xe4f0C9e3B7fD37AC443E20D2EA6E572Dce263e11/sources/browser/ToshiCoin.sol
* @dev Anyone can purchase ToshiCoin for TOSHI until it is sold out./
function purchase(uint256 amount) external { uint256 price = priceInTOSHI.mul(amount); uint256 balance = toshi.balanceOf(msg.sender); require(balance >= price, "ToshiCoin: Not enough TOSHI in wallet."); require( remainingToshiCoinForSale >= amount, "ToshiCoin: Not enough ToshiCoin for sale." ); safeToshiTransferFrom(msg.sender, toshiTreasury, price); remainingToshiCoinForSale = remainingToshiCoinForSale.sub(amount); _mint(msg.sender, amount); addMinted(amount); } BLUE DERPY, [10.12.20 10:40]
12,355,280
[ 1, 2961, 476, 848, 23701, 399, 538, 12266, 27055, 364, 8493, 2664, 45, 3180, 518, 353, 272, 1673, 596, 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 ]
[ 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, 23701, 12, 11890, 5034, 3844, 13, 3903, 288, 203, 3639, 2254, 5034, 6205, 273, 6205, 382, 4296, 2664, 45, 18, 16411, 12, 8949, 1769, 203, 3639, 2254, 5034, 11013, 273, 358, 674, 77, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 2583, 12, 12296, 1545, 6205, 16, 315, 56, 538, 12266, 27055, 30, 2288, 7304, 8493, 2664, 45, 316, 9230, 1199, 1769, 203, 3639, 2583, 12, 203, 5411, 4463, 56, 538, 12266, 27055, 1290, 30746, 1545, 3844, 16, 203, 5411, 315, 56, 538, 12266, 27055, 30, 2288, 7304, 399, 538, 12266, 27055, 364, 272, 5349, 1199, 203, 3639, 11272, 203, 203, 3639, 4183, 56, 538, 12266, 5912, 1265, 12, 3576, 18, 15330, 16, 358, 674, 77, 56, 266, 345, 22498, 16, 6205, 1769, 203, 203, 3639, 4463, 56, 538, 12266, 27055, 1290, 30746, 273, 4463, 56, 538, 12266, 27055, 1290, 30746, 18, 1717, 12, 8949, 1769, 203, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 3639, 527, 49, 474, 329, 12, 8949, 1769, 203, 565, 289, 203, 203, 14618, 1821, 21801, 16235, 16, 306, 2163, 18, 2138, 18, 3462, 1728, 30, 7132, 65, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-02-08 */ // 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/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC2981.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @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/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // File: contracts/derschutzeNFT.sol pragma solidity ^0.8.0; /* __ __ __ _ ____________ ___/ /__ _______ ____/ / __ __/ /____ ___ / |/ / __/_ __/ / _ / -_) __(_-</ __/ _ \/ // / __/_ // -_) / / _/ / / \_,_/\__/_/ /___/\__/_//_/\_,_/\__//__/\__/ /_/|_/_/ /_/ */ /** * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the * fee is specified in basis points by default. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC2981 is IERC2981, ERC165 { struct RoyaltyInfo { address receiver; uint96 royaltyFraction; } RoyaltyInfo private _defaultRoyaltyInfo; mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @inheritdoc IERC2981 */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address, uint256) { RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } /** * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an * override. */ function _feeDenominator() internal pure virtual returns (uint96) { return 10000; } /** * @dev Sets the royalty information that all ids in this contract will default to. * * Requirements: * * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { require( feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice" ); require(receiver != address(0), "ERC2981: invalid receiver"); _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Removes default royalty information. */ function _deleteDefaultRoyalty() internal virtual { delete _defaultRoyaltyInfo; } /** * @dev Sets the royalty information for a specific token id, overriding the global default. * * Requirements: * * - `tokenId` must be already minted. * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator ) internal virtual { require( feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice" ); require(receiver != address(0), "ERC2981: Invalid parameters"); _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Resets royalty information for the token id back to the global default. */ function _resetTokenRoyalty(uint256 tokenId) internal virtual { delete _tokenRoyaltyInfo[tokenId]; } } contract derschutzeOne is ERC1155Supply, ERC2981, Ownable, Pausable { event Mint(uint256 tokenId, uint256 amount, address recipient); address private _royaltiesReceiver; mapping(address => uint8) private whiteList; uint96 public constant royaltiesPercentage = 75; // 7.5 % uint8 public constant MAX_SUPPLY = 100; uint256 public perNftPrice = 0.05 ether; string private name_; string private symbol_; constructor( string memory _baseTokenUri, string memory _symbol, string memory _name ) ERC1155(_baseTokenUri) { _royaltiesReceiver = msg.sender; _setDefaultRoyalty(_royaltiesReceiver, royaltiesPercentage); name_ = _name; symbol_ = _symbol; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } // set baseTokenUri, incase it needs to change in the future function setBaseUri(string memory _baseTokenUri) external onlyOwner { _setURI(_baseTokenUri); } // set per nft price, incase it needs to change in the future function setPerNftPrice(uint256 newPernftPrice) external onlyOwner { perNftPrice = newPernftPrice; } // check if the wallet is whitelisted and return the ID function whitelisted(address _address) external view returns(uint8) { return whiteList[_address]; } // add whitelist addresses to mint the nft of specific ids function addWhiteListed( address[] calldata _whiteListAddresses, uint8[] calldata _whiteListIds ) external onlyOwner { for (uint8 i = 0; i < _whiteListAddresses.length; i++) { whiteList[_whiteListAddresses[i]] = _whiteListIds[i]; } } // return the royalties Receiver function royaltiesReceiver() external view returns (address) { return _royaltiesReceiver; } // set the royalty beneficiary function setRoyaltiesReceiver(address newRoyaltiesReceiver) external onlyOwner { require(newRoyaltiesReceiver != _royaltiesReceiver); _royaltiesReceiver = newRoyaltiesReceiver; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC2981) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function _feeDenominator() internal pure virtual override returns (uint96) { return 1000; } // get the nft meta data for the specified id function uri(uint256 _id) public view override returns (string memory) { require(exists(_id), "URI: nonexistent token"); return string(abi.encodePacked(super.uri(_id), Strings.toString(_id))); } // return cap amount of specific id function getCapAmountOfToken(uint256 id) public pure returns (uint256) { if (id == 1) return 5; if (id == 2) return 21; if (id == 3) return 30; if (id == 4) return 29; if (id == 5) return 15; else revert("Wrong id"); } // Mint function only be called by whiteListed users function mint() external payable whenNotPaused { uint8 id = whiteList[msg.sender]; require(id != 0, "Not whitelisted"); require( totalSupply(id) < getCapAmountOfToken(id), "All tokens minted of this type" ); require(tx.origin == address(msg.sender)); require(msg.value == perNftPrice, "Invalid amount of ether send"); whiteList[msg.sender] = 0; _mint(msg.sender, id, 1, ""); emit Mint(id, 1, msg.sender); } // contract owner can with draw funds in the contract function ownerWithdraw() public onlyOwner { require(address(this).balance != 0,"No eth to withdraw"); payable(owner()).transfer(address(this).balance); } receive() external payable {} }
get the nft meta data for the specified id
function uri(uint256 _id) public view override returns (string memory) { require(exists(_id), "URI: nonexistent token"); return string(abi.encodePacked(super.uri(_id), Strings.toString(_id))); }
6,792,691
[ 1, 588, 326, 290, 1222, 2191, 501, 364, 326, 1269, 612, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 2003, 12, 11890, 5034, 389, 350, 13, 1071, 1476, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 12, 1808, 24899, 350, 3631, 315, 3098, 30, 1661, 19041, 1147, 8863, 203, 203, 3639, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 9565, 18, 1650, 24899, 350, 3631, 8139, 18, 10492, 24899, 350, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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 { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title 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(_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 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. * https://github.com/ethereum/EIPs/issues/20 * 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(_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 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, uint256 _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, uint256 _subtractedValue ) public returns (bool) { uint256 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; } } contract BlockchainToken is StandardToken, Ownable { string public constant name = 'Blockchain Token 2.0'; string public constant symbol = 'BCT'; uint32 public constant decimals = 18; /** * how many USD cents for 1 * 10^18 token */ uint public price = 210; function setPrice(uint _price) onlyOwner public { price = _price; } uint256 public INITIAL_SUPPLY = 21000000 * 1 ether; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(address(0), msg.sender, INITIAL_SUPPLY); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * 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 Burn(address indexed burner, uint256 value); 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 ) public hasMintPermission canMint 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 Burns a specific amount of tokens. * @param _addr The address that will have _amount of tokens burned * @param _value The amount of token to be burned. */ function burn( address _addr, uint256 _value ) public onlyOwner { _burn(_addr, _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); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract WealthBuilderToken is MintableToken { string public name = 'Wealth Builder Token'; string public symbol = 'WBT'; uint32 public decimals = 18; /** * how many {tokens*10^(-18)} get per 1wei */ uint public rate = 10 ** 7; /** * multiplicator for rate */ uint public mrate = 10 ** 7; function setRate(uint _rate) onlyOwner public { rate = _rate; } } contract Data is Ownable { // node => its parent mapping (address => address) private parent; // node => its status mapping (address => uint8) public statuses; // node => sum of all his child deposits in USD cents mapping (address => uint) public referralDeposits; // client => balance in wei*10^(-6) available for withdrawal mapping(address => uint256) private balances; // investor => balance in wei*10^(-6) available for withdrawal mapping(address => uint256) private investorBalances; function parentOf(address _addr) public constant returns (address) { return parent[_addr]; } function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr] / 1000000; } function investorBalanceOf(address _addr) public constant returns (uint256) { return investorBalances[_addr] / 1000000; } /** * @dev The Data constructor to set up the first depositer */ constructor() public { // DirectorOfRegion - 7 statuses[msg.sender] = 7; } function addBalance(address _addr, uint256 amount) onlyOwner public { balances[_addr] += amount; } function subtrBalance(address _addr, uint256 amount) onlyOwner public { require(balances[_addr] >= amount); balances[_addr] -= amount; } function addInvestorBalance(address _addr, uint256 amount) onlyOwner public { investorBalances[_addr] += amount; } function subtrInvestorBalance(address _addr, uint256 amount) onlyOwner public { require(investorBalances[_addr] >= amount); investorBalances[_addr] -= amount; } function addReferralDeposit(address _addr, uint256 amount) onlyOwner public { referralDeposits[_addr] += amount; } function subtrReferralDeposit(address _addr, uint256 amount) onlyOwner public { referralDeposits[_addr] -= amount; } function setStatus(address _addr, uint8 _status) onlyOwner public { statuses[_addr] = _status; } function setParent(address _addr, address _parent) onlyOwner public { parent[_addr] = _parent; } } contract Declaration { // threshold in USD => status mapping (uint => uint8) statusThreshold; // status => (depositsNumber => percentage / 10) mapping (uint8 => mapping (uint16 => uint256)) feeDistribution; // status thresholds in USD uint[8] thresholds = [ 0, 5000, 35000, 150000, 500000, 2500000, 5000000, 10000000 ]; uint[5] referralFees = [50, 30, 20, 10, 5]; uint[5] serviceFees = [25, 20, 15, 10, 5]; /** * @dev The Declaration constructor to define some constants */ constructor() public { setFeeDistributionsAndStatusThresholds(); } /** * @dev Set up fee distribution & status thresholds */ function setFeeDistributionsAndStatusThresholds() private { // Agent - 0 setFeeDistributionAndStatusThreshold(0, [uint16(120), uint16(80), uint16(50), uint16(20), uint16(10)], thresholds[0]); // SilverAgent - 1 setFeeDistributionAndStatusThreshold(1, [uint16(160), uint16(100), uint16(60), uint16(30), uint16(20)], thresholds[1]); // Manager - 2 setFeeDistributionAndStatusThreshold(2, [uint16(200), uint16(120), uint16(80), uint16(40), uint16(25)], thresholds[2]); // ManagerOfGroup - 3 setFeeDistributionAndStatusThreshold(3, [uint16(250), uint16(150), uint16(100), uint16(50), uint16(30)], thresholds[3]); // ManagerOfRegion - 4 setFeeDistributionAndStatusThreshold(4, [300, 180, 120, 60, 35], thresholds[4]); // Director - 5 setFeeDistributionAndStatusThreshold(5, [350, 210, 140, 70, 40], thresholds[5]); // DirectorOfGroup - 6 setFeeDistributionAndStatusThreshold(6, [400, 240, 160, 80, 45], thresholds[6]); // DirectorOfRegion - 7 setFeeDistributionAndStatusThreshold(7, [500, 300, 200, 100, 50], thresholds[7]); } /** * @dev Set up specific fee and status threshold * @param _st The status to set up for * @param _percentages Array of pecentages, which should go to member * @param _threshold The minimum amount of sum of children deposits to get * the status _st */ function setFeeDistributionAndStatusThreshold( uint8 _st, uint16[5] _percentages, uint _threshold ) private { statusThreshold[_threshold] = _st; for (uint8 i = 0; i < _percentages.length; i++) { feeDistribution[_st][i] = _percentages[i]; } } } contract Referral is Declaration, Ownable { using SafeMath for uint; // reference to WBT token contract WealthBuilderToken private wbtToken; // reference to BCT2.0 token contract BlockchainToken private bctToken; // reference to data contract Data private data; /** * how many USD cents get per ETH */ uint public ethUsdRate; /** * @dev The Referral constructor to set up the first depositer, * reference to system wbt token, bct token, data and set ethUsdRate */ constructor( uint _ethUsdRate, address _wbtToken, address _bctToken, address _data ) public { ethUsdRate = _ethUsdRate; // instantiate wbtToken & data contracts wbtToken = WealthBuilderToken(_wbtToken); bctToken = BlockchainToken(_bctToken); data = Data(_data); } /** * @dev Callback function */ function() payable public { } /** * @dev invest wbt token function * @param _client to transfer WBT token * @param _depositsCount num of the deposit */ function invest( address _client, uint8 _depositsCount ) payable public { uint amount = msg.value; // if less then 5 deposits if (_depositsCount < 5) { uint serviceFee; serviceFee = amount * serviceFees[_depositsCount]; uint referralFee = amount * referralFees[_depositsCount]; // distribute deposit fee among users above on the branch & update users' statuses distribute(data.parentOf(_client), 0, _depositsCount, amount); // update balance & number of deposits of user uint active = (amount * 100).sub(referralFee).sub(serviceFee); wbtToken.mint(_client, active / 100 * wbtToken.rate() / wbtToken.mrate()); // update owner`s balance data.addBalance(owner, serviceFee * 10000); } else { wbtToken.mint(_client, amount * wbtToken.rate() / wbtToken.mrate()); } } /** * @dev invest bct token function * @param _client to transfer BCT token */ function investBct( address _client ) public payable { uint amount = msg.value; // distribute deposit fee among users above on the branch & update users' statuses distribute(data.parentOf(_client), 0, 0, amount); bctToken.transfer(_client, amount * ethUsdRate / bctToken.price()); } /** * @dev Recursively distribute deposit fee between parents * @param _node Parent address * @param _prevPercentage The percentage for previous parent * @param _depositsCount Count of depositer deposits * @param _amount The amount of deposit */ function distribute( address _node, uint _prevPercentage, uint8 _depositsCount, uint _amount ) private { address node = _node; uint prevPercentage = _prevPercentage; // distribute deposit fee among users above on the branch & update users' statuses while(node != address(0)) { uint8 status = data.statuses(node); // count fee percentage of current node uint nodePercentage = feeDistribution[status][_depositsCount]; uint percentage = nodePercentage.sub(prevPercentage); data.addBalance(node, _amount * percentage * 1000); //update refferals sum amount data.addReferralDeposit(node, _amount * ethUsdRate / 10**18); //update status updateStatus(node, status); node = data.parentOf(node); prevPercentage = nodePercentage; } } /** * @dev Update node status if children sum amount is enough * @param _node Node address * @param _status Node current status */ function updateStatus( address _node, uint8 _status ) private { uint refDep = data.referralDeposits(_node); for (uint i = thresholds.length - 1; i > _status; i--) { uint threshold = thresholds[i] * 100; if (refDep >= threshold) { data.setStatus(_node, statusThreshold[thresholds[i]]); break; } } } /** * @dev Set wbtToken exchange rate * @param _rate wbt/eth rate */ function setRate( uint _rate ) onlyOwner public { wbtToken.setRate(_rate); } /** * @dev Set bctToken price * @param _price bct/usd rate */ function setPrice( uint _price ) onlyOwner public { bctToken.setPrice(_price); } /** * @dev Set ETH exchange rate * @param _ethUsdRate eth/usd rate */ function setEthUsdRate( uint _ethUsdRate ) onlyOwner public { ethUsdRate = _ethUsdRate; } /** * @dev Add new child * @param _inviter parent * @param _invitee child */ function invite( address _inviter, address _invitee ) public onlyOwner { data.setParent(_invitee, _inviter); // Agent - 0 data.setStatus(_invitee, 0); } /** * @dev Set _status for _addr * @param _addr address * @param _status ref. status */ function setStatus( address _addr, uint8 _status ) public onlyOwner { data.setStatus(_addr, _status); } /** * @dev Withdraw _amount for _addr * @param _addr withdrawal address * @param _amount withdrawal amount * @param investor is investor */ function withdraw( address _addr, uint256 _amount, bool investor ) public onlyOwner { uint amount = investor ? data.investorBalanceOf(_addr) : data.balanceOf(_addr); require(amount >= _amount && address(this).balance >= _amount); if (investor) { data.subtrInvestorBalance(_addr, _amount * 1000000); } else { data.subtrBalance(_addr, _amount * 1000000); } _addr.transfer(_amount); } /** * @dev Withdraw contract balance to _addr * @param _addr withdrawal address */ function withdrawOwner( address _addr, uint256 _amount ) public onlyOwner { require(address(this).balance >= _amount); _addr.transfer(_amount); } /** * @dev Withdraw corresponding amount of ETH to _addr and burn _value tokens * @param _addr buyer address * @param _amount amount of tokens to buy */ function transferBctToken( address _addr, uint _amount ) onlyOwner public { require(bctToken.balanceOf(this) >= _amount); bctToken.transfer(_addr, _amount); } /** * @dev Withdraw corresponding amount of ETH to _addr and burn _value tokens * @param _addr withdrawal address * @param _amount amount of tokens to sell */ function withdrawWbtToken( address _addr, uint256 _amount ) onlyOwner public { wbtToken.burn(_addr, _amount); uint256 etherValue = _amount * wbtToken.mrate() / wbtToken.rate(); _addr.transfer(etherValue); } /** * @dev Transfer ownership of wbtToken contract to _addr * @param _addr address */ function transferTokenOwnership( address _addr ) onlyOwner public { wbtToken.transferOwnership(_addr); } /** * @dev Transfer ownership of data contract to _addr * @param _addr address */ function transferDataOwnership( address _addr ) onlyOwner public { data.transferOwnership(_addr); } }
* @dev Update node status if children sum amount is enough @param _node Node address @param _status Node current status/
function updateStatus( address _node, uint8 _status ) private { uint refDep = data.referralDeposits(_node); for (uint i = thresholds.length - 1; i > _status; i--) { uint threshold = thresholds[i] * 100; if (refDep >= threshold) { data.setStatus(_node, statusThreshold[thresholds[i]]); break; } } }
10,359,555
[ 1, 1891, 756, 1267, 309, 2325, 2142, 3844, 353, 7304, 225, 389, 2159, 2029, 1758, 225, 389, 2327, 2029, 783, 1267, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 1482, 12, 203, 3639, 1758, 389, 2159, 16, 203, 3639, 2254, 28, 389, 2327, 203, 565, 262, 203, 3639, 3238, 203, 565, 288, 203, 3639, 2254, 1278, 16316, 273, 501, 18, 1734, 29084, 758, 917, 1282, 24899, 2159, 1769, 203, 203, 3639, 364, 261, 11890, 277, 273, 19983, 18, 2469, 300, 404, 31, 277, 405, 389, 2327, 31, 277, 413, 13, 288, 203, 5411, 2254, 5573, 273, 19983, 63, 77, 65, 380, 2130, 31, 203, 203, 5411, 309, 261, 1734, 16316, 1545, 5573, 13, 288, 203, 7734, 501, 18, 542, 1482, 24899, 2159, 16, 1267, 7614, 63, 8699, 87, 63, 77, 13563, 1769, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 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 ]