file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/1/0x7B1d261f715a5090106FD4E45CDcEe14b56441db/sources/Token (2).sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Babylicious", "Belicious") { IUniswapV2Router02 _router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address _pair = IUniswapV2Factory(_router.factory()).createPair(address(this), _router.WETH()); router = _router; pair = _pair; _setAutomatedMarketMakerPair(_pair, true); excludeFromFees(owner(), true); excludeFromFees(address(this), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(owner(), 1 * 10 ** 12 * (10 ** 18)); maxWalletLimit = totalSupply().mul(2).div(100); maxTxAmount = totalSupply().mul(2).div(100); swapTokensAtAmount = totalSupply().mul(1).div(10000);
16,444,106
pragma solidity ^0.4.16; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20() public { totalSupply = 200000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "WaraCoin2"; // Set the name for display purposes symbol = "WAC2"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } } contract WaraCoin is owned, TokenERC20 { uint256 public sale_step; address waracoin_corp; /* Save product's genuine information */ struct Product_genuine { address m_made_from_who; // who made this product string m_Product_GUID; // product's unique code string m_Product_Description; // product's description address m_who_have; // who have this product now address m_send_to_who; // when product move to agency - if it is different with seller, it means that seller have no genuine string m_hash; // need to check hash of description uint256 m_moved_count; // how many times moved this product } mapping (address => mapping (uint256 => Product_genuine)) public MyProducts; /* Initializes contract with initial supply tokens to the creator of the contract */ function WaraCoin() TokenERC20() public { sale_step = 0; // 0 : No sale, 1 : Presale, 2 : Crowdsale, 3 : Normalsale waracoin_corp = msg.sender; } function SetSaleStep(uint256 step) onlyOwner public { sale_step = step; } /* Set Waracoin sale price */ function () payable { require(sale_step!=0); if ( msg.sender != owner ) // If owner send Ether, it will use for dApp operation { uint amount = 0; uint nowprice = 0; if ( sale_step == 1 ) nowprice = 10000; // presale price else if ( sale_step == 2 ) nowprice = 5000; // crowdsale price else nowprice = 1000; // normalsale price amount = msg.value * nowprice; require(balanceOf[waracoin_corp]>=amount); balanceOf[waracoin_corp] -= amount; balanceOf[msg.sender] += amount; // adds the amount to buyer's balance require(waracoin_corp.send(msg.value)); Transfer(this, msg.sender, amount); // execute an event reflecting the change } } /** * Seller will send WaraCoin to buyer * * @param _to The address of backers who have WaraCoin * @param coin_amount How many WaraCoin will send */ function waraCoinTransfer(address _to, uint256 coin_amount) public { uint256 amount = coin_amount * 10 ** uint256(decimals); require(balanceOf[msg.sender] >= amount); // checks if the sender has enough to sell balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance balanceOf[_to] += amount; // subtracts the amount from seller's balance Transfer(msg.sender, _to, amount); // executes an event reflecting on the change } /** * Owner will buy back WaraCoin from backers * * @param _from The address of backers who have WaraCoin * @param coin_amount How many WaraCoin will buy back from him */ function DestroyCoin(address _from, uint256 coin_amount) onlyOwner public { uint256 amount = coin_amount * 10 ** uint256(decimals); require(balanceOf[_from] >= amount); // checks if the sender has enough to sell balanceOf[_from] -= amount; // subtracts the amount from seller's balance Transfer(_from, this, amount); // executes an event reflecting on the change } /** * Here is WaraCoin's Genuine dApp functions */ /* When creator made product, must need to use this fuction for register his product first */ function registerNewProduct(uint256 product_idx,string new_guid,string product_descriptions,string hash) public returns(bool success) { uint256 amount = 1 * 10 ** uint256(decimals-2); require(balanceOf[msg.sender]>=amount); // Need to use one WaraCoin for make product code Product_genuine storage mine = MyProducts[msg.sender][product_idx]; require(mine.m_made_from_who!=msg.sender); mine.m_made_from_who = msg.sender; mine.m_who_have = msg.sender; mine.m_Product_GUID = new_guid; mine.m_Product_Description = product_descriptions; mine.m_hash = hash; balanceOf[msg.sender] -= amount; return true; } /* If product's owner want to move, he need to use this fuction for setting receiver : must use by sender */ function setMoveProductToWhom(address who_made_this,uint256 product_idx,address moveto) public returns (bool success) { Product_genuine storage mine = MyProducts[who_made_this][product_idx]; require(mine.m_who_have==msg.sender); mine.m_send_to_who = moveto; return true; } /* Product's buyer need to use this function for save his genuine */ function moveProduct(address who_made_this,address who_have_this,uint256 product_idx) public returns (bool success) { uint256 amount = 1 * 10 ** uint256(decimals-2); require(balanceOf[msg.sender]>=amount); // Need to use one WaraCoin for move product Product_genuine storage mine = MyProducts[who_made_this][product_idx]; require(mine.m_who_have==who_have_this); // if sender have no product, break require(mine.m_send_to_who==msg.sender); // if receiver is not me, break mine.m_who_have = msg.sender; mine.m_moved_count += 1; balanceOf[msg.sender] -= amount; return true; } /* Check Genuine of owner */ function checkProductGenuine(address who_made_this,address who_have_this,uint256 product_idx) public returns (bool success) { success = false; Product_genuine storage mine = MyProducts[who_made_this][product_idx]; if ( mine.m_who_have==who_have_this ) // if checker have no product, break success = true; return success; } }
Check Genuine of owner /
function checkProductGenuine(address who_made_this,address who_have_this,uint256 product_idx) public returns (bool success) { success = false; Product_genuine storage mine = MyProducts[who_made_this][product_idx]; success = true; return success; }
13,547,696
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title NoteTogether * @dev handles storage of video metadata for the NoteTogether web app */ contract NoteTogether { struct Video { string IPFSkey; //hash key for retrieving video from IPFS directory string title; //sharable link that is used to access video metadata address user; //video uploader } struct Note { string timestamp; //timestamp of the video tied to a note string tag; //message type string message; //content of the note address user; //user tied to the note } struct Analytics { string viewData; //analytics metadata for viewership string noteData; //analytics metadata for note taking } mapping(string => Video) videoMap; //map of videos to their id by page link mapping(string => Note[]) noteMap; //map of note lists to video id mapping(string => Analytics) analyticsMap; //map of view analytics to video via key mapping(address => string) usernameMap; //map of user addresses to usernames mapping(address => string[]) interactionMap; //map of users to a list of keys for videos they uploaded, added a note to, or saved /** * @dev creates video metadata storage with an IPFS key and the page link * @param key, key */ function addVideo(string memory key, string memory title) public { Video memory vid = Video(key, title, msg.sender); videoMap[key] = vid; interactionMap[msg.sender].push(key); } /** * @dev pulls Video metadata of a corresponding page link * @param link key */ function getVideoData(string memory link) public returns (Video memory video) { return videoMap[link]; } /** * @dev stores a note for a video * @param key, timestamp, tag, content, user */ function addNote( string memory key, string memory timestamp, string memory tag, string memory message, address user ) public { Note memory note = Note(timestamp, tag, message, user); noteMap[key].push(note); if (interactionMap[user].length == 0) { interactionMap[user].push(key); } else { for (uint256 i = 0; i < interactionMap[user].length; i++) { if ( keccak256(abi.encodePacked(interactionMap[user][i])) == keccak256(abi.encodePacked(key)) ) { return; } } interactionMap[user].push(key); } } /** * @dev pulls the list of notes cooresponding to a video * @param link page link tied to video */ function getNotes(string memory link) public returns (Note[] memory) { return noteMap[link]; } /** * @dev updates analytics with latest data from Calc Engine * @param link, noteData, viewData */ function updateAnalytics( string memory link, string memory noteData, string memory viewData ) public { Analytics memory ana = Analytics(viewData, noteData); analyticsMap[link] = ana; } /** * @dev returns the username tied to message sender */ function getUsername() public returns (string memory username) { return usernameMap[msg.sender]; } /** * @dev returns the username tied to message sender */ function getUsernameById(address user) public returns (string memory username) { return usernameMap[user]; } /** * @dev changes username of message sender * @param username name tied to user address */ function changeUsername(string memory username) public { usernameMap[msg.sender] = username; } /** * @dev returns all videos the user has interacted with * */ function getInteractions(address user) public returns (string[] memory) { return interactionMap[user]; } }
pulls the list of notes cooresponding to a video link page link tied to video/
function getNotes(string memory link) public returns (Note[] memory) { return noteMap[link]; }
6,434,791
pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "./ownable.sol"; contract HappyAlliance is Ownable { struct Donation { // Do not record details in the blockchain string donationId; // donation Id string memberId; // member Id string openInfo; // information that a member agrees to open } Donation[] public donations; // donation array mapping (string => string[]) memberToDonations; struct Box { string boxId; // box Id string boxType; // box type such as KIDS string generatedYear; // year that a box is generated string serializedDonationsDetails; // originally string[] donationIds; string expirationDate; // expiration date obtained from the minimum value out of donations string npoInfo; // npo information string npoReceivedTime; // check whether the npo receives string recipientInfo; // information about last recipients string recipientReceivedTime; // check whether the recipient receives } Box[] public boxes; // box array mapping (string => uint) yearlyCounts; mapping (string => string) boxToNPO; mapping (string => string[]) npoToBoxIds; mapping (string => uint) boxIdToIdx; mapping (string => string[]) historyOfBox; // record whole destination history string[] public boxIdList; // list of box ids string[] public boxTypes; // list of box types uint[] public boxStatus; constructor () public { // initialize the first box of which id is "test" distributeBox("initialize", "undefined", "undefined", '[{"undefined": ""}]', "null", "undefined"); boxStatus[0] = 99; donate("initialize", "noname", "noInfo"); } function donate (string _donationId, string _memberId, string _openInfo) public { Donation memory tmpDonation; tmpDonation.donationId = _donationId; tmpDonation.memberId = _memberId; tmpDonation.openInfo = _openInfo; donations.push(tmpDonation); memberToDonations[_memberId].push(_donationId); } function distributeBox (string _boxId, string _boxType, string _year, string _serializedDonationsDetails, string _expirationDate, string _npo) public { Box memory tmpBox; tmpBox.boxId = _boxId; tmpBox.boxType = _boxType; tmpBox.generatedYear = _year; tmpBox.serializedDonationsDetails = _serializedDonationsDetails; tmpBox.expirationDate = _expirationDate; tmpBox.npoInfo = _npo; tmpBox.npoReceivedTime = ''; tmpBox.recipientInfo = ''; tmpBox.recipientReceivedTime = ''; boxes.push(tmpBox); boxStatus.push(0); boxToNPO[_boxId] = _npo; npoToBoxIds[_npo].push(_boxId); boxIdToIdx[_boxId] = boxes.length - 1; historyOfBox[_boxId].push(_npo); boxIdList.push(_boxId); boxTypes.push(_boxType); yearlyCounts[_year]++; } // confirm that a npo receives a box function receiveBox (string _boxId, string _time) public { boxes[boxIdToIdx[_boxId]].npoReceivedTime = _time; if(boxStatus[boxIdToIdx[_boxId]]<=1){ boxStatus[boxIdToIdx[_boxId]] = 1; } } function addInfo (string _boxId, string _recipientInfo, string _time) public { boxes[boxIdToIdx[_boxId]].recipientInfo = _recipientInfo; boxes[boxIdToIdx[_boxId]].recipientReceivedTime = _time; boxStatus[boxIdToIdx[_boxId]] = 2; historyOfBox[_boxId].push(_recipientInfo); } // return all box ids; function getBoxIds () public view returns(string[]){ return boxIdList; } // return box types; function getBoxTypes () public view returns(string[]){ return boxTypes; } // return the received history of a box function getHistoryOfBox (string _boxId) public view returns(string[]){ return historyOfBox[_boxId]; } // After a recipient receives the box and notifies this update to SK function getStatusForAll () public view returns (uint[]) { return boxStatus; } // check box information function viewBoxInformation (string _boxId) public view returns(string, string, string, string, string, string){ //require(boxes[boxIdToIdx[_boxId]].received == true, "NPO does not receive the box yet."); Box memory targetBox = boxes[boxIdToIdx[_boxId]]; return (_boxId, targetBox.serializedDonationsDetails, targetBox.npoInfo, targetBox.npoReceivedTime, targetBox.recipientInfo, targetBox.recipientReceivedTime); } // mapping box id to index in 'boxes' array function getIndexByBoxId (string _boxId) public view returns (uint) { return boxIdToIdx[_boxId]; } // get number of boxes by year function getNumBoxesByYear (string _year) public view returns (uint) { return yearlyCounts[_year]; } function getBoxInfoByNPO (string _npo) public view returns (string[], string[], string[], string[], string[], string[]) { string[] memory tmp = npoToBoxIds[_npo]; string[] memory list1 = new string[](tmp.length); string[] memory list2 = new string[](tmp.length); string[] memory list3 = new string[](tmp.length); string[] memory list4 = new string[](tmp.length); string[] memory list5 = new string[](tmp.length); string[] memory list6 = new string[](tmp.length); for(uint i=0; i<tmp.length; i++){ list1[i] = boxes[boxIdToIdx[tmp[i]]].boxId; list2[i] = boxes[boxIdToIdx[tmp[i]]].boxType; list3[i] = boxes[boxIdToIdx[tmp[i]]].serializedDonationsDetails; list4[i] = boxes[boxIdToIdx[tmp[i]]].npoReceivedTime; list5[i] = boxes[boxIdToIdx[tmp[i]]].recipientInfo; list6[i] = boxes[boxIdToIdx[tmp[i]]].recipientReceivedTime; } return (list1, list2, list3, list4, list5, list6); } function getAllBoxInfo () public view returns (string[], string[], string[], string[]){ string[] memory boxIds = getBoxIds(); string[] memory types = new string[](boxIds.length); string[] memory donations = new string[](boxIds.length); string[] memory npos = new string[](boxIds.length); for(uint i=0; i<boxIds.length; i++){ types[i] = boxes[boxIdToIdx[boxIds[i]]].boxType; donations[i] = boxes[boxIdToIdx[boxIds[i]]].serializedDonationsDetails; npos[i] = boxes[boxIdToIdx[boxIds[i]]].npoInfo; } return (boxIds, types, donations, npos); } }
return all box ids;
function getBoxIds () public view returns(string[]){ return boxIdList; }
7,300,889
./full_match/3/0x8E82802982f809DDCe7E295277dD9C2614d2BBB8/sources/browser/ReflectiveTreasury-flattened.sol
Transfers tokens to beneficiary./
function release() public { uint256 amount = fundsAvailable(); if (amount > 0) { _token.safeTransfer(_beneficiary, amount); } }
8,231,237
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; using SafeMath for uint32; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct Airline { address airlineAddress; string airlineName; bool funded; } struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; uint32 flightNumber; address[] passengers; // 20 Seats per flight } struct PassengerProfile { uint256 balance; } address[] private airlinesRegistered; mapping(address => Airline) private airlines; uint32[] private flightsRegistered; mapping(uint32 => Flight) private flights; mapping(address => PassengerProfile) private passengers; mapping(address => uint256) private authorized; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; } /********************************************************************************************/ /* 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(isOperational(), "Contract is currently not operational"); // _; // All modifiers require an "_" which indicates where the function body will be added // } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } //Modifier for checking an airline has funded or Not modifier requireAirlineFunded(address _airlineAddress) { require(airlines[_airlineAddress].funded == true , "Airline is not Funded"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() view external returns(bool) { return operational; } //Authorize caller function authorizeCaller ( address contractAddress ) external requireContractOwner { authorized[contractAddress] = 1; } function deauthorizeCaller ( address contractAddress ) external requireContractOwner { authorized[contractAddress] = 0; } /** * @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; } //Return Registered airlinesRegistered function getAirlinesRegistered ( ) public view returns(address[]) { return airlinesRegistered; } //Return Registered flights function getFlightsRegistered ( ) public view returns(uint32[]) { return flightsRegistered; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ uint constant M = 4; mapping(address => address[]) multiCalls; /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address _airlineAddress, string _airlineName, address _registeringAirline, bool _funded ) external { //Check for unique bool unique = true; for(uint i=0; i<airlinesRegistered.length; i++) { if(airlinesRegistered[i] == _airlineAddress) unique = false; } require(unique, "Airline already Added"); //Check if the registering airline is funded require(airlines[_registeringAirline].funded == true || _registeringAirline == contractOwner, "Cannot register an Airline unless funded by sending airline"); if (airlinesRegistered.length < M) { airlinesRegistered.push(_airlineAddress); airlines[_airlineAddress] = Airline ({ airlineAddress: _airlineAddress, airlineName: _airlineName, funded: _funded }); } //ADD TO MULTI CALLS else { bool isDuplicate = false; for(uint j=0; j< multiCalls[_airlineAddress].length; j++) { if (multiCalls[_airlineAddress][j] == _registeringAirline) { isDuplicate = true; break; } } require(!isDuplicate, "Caller has already called this function."); multiCalls[_airlineAddress].push(_registeringAirline); if (multiCalls[_airlineAddress].length >= airlinesRegistered.length /2 ) { airlinesRegistered.push(_airlineAddress); airlines[_airlineAddress] = Airline ({ airlineAddress: _airlineAddress, airlineName: _airlineName, funded: _funded }); } } } // Check if it is an airline function isAirline ( address airlineAddress ) external view returns(bool) { bool status = false; for(uint i=0; i < airlinesRegistered.length; i++) { if (airlinesRegistered[i] == airlineAddress) { status = true; } } return status; } /** * @dev Register a future flight for insuring. * */ function registerFlight ( uint32 _flightNumber, address _airlineAddress ) external { flightsRegistered.push(_flightNumber); flights[_flightNumber] = Flight({ isRegistered: true, statusCode: 0, updatedTimestamp: now, airline: _airlineAddress , flightNumber: _flightNumber, passengers: new address[](0) }); } /** * @dev Buy insurance for a flight * */ function buy ( uint32 _flightNumber, address _passenger ) external { //Check for unique bool unique = true; for(uint i=0; i<flights[_flightNumber].passengers.length; i++) { if(flights[_flightNumber].passengers[i] == _passenger) unique = false; } require(unique, "Insurance already purchased for this flight"); flights[_flightNumber].passengers.push(_passenger); // Push the passenger address into insured list passengers[_passenger] = PassengerProfile({ balance: 0 }); } uint256 private INSURANCE_COST = 1; /** * @dev Credits payouts to insurees */ function creditInsurees ( uint32 _flightNumber ) external { for(uint i=0; i<flights[_flightNumber].passengers.length; i++) { uint256 INSURANCE_PAYOUT = INSURANCE_COST.div(2).mul(3); passengers[flights[_flightNumber].passengers[i]].balance += INSURANCE_PAYOUT; } } // Return the balance for the passenger function balance ( address _passenger ) external returns (uint256 balance) { return passengers[_passenger].balance; } /** * @dev Transfers eligible payout funds to insuree * */ // Claim if balance availble function pay ( address _passenger ) external returns (uint256) { // check if it is a valid passenger require(passengers[_passenger].balance > 0, "No balance in wallet"); uint256 balance_passenger = passengers[_passenger].balance; return balance_passenger; } // Get fund from Airline function airlineFund ( address _airlineAddress ) payable public returns(bool success) { require(airlines[_airlineAddress].funded == false , "Airline is already Funded"); airlines[_airlineAddress].funded = true; return true; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( ) public payable { } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
Return the balance for the passenger
function balance ( address _passenger ) external returns (uint256 balance) { return passengers[_passenger].balance; }
12,737,969
pragma solidity ^0.4.0; /* * Token - is a smart contract interface * for managing common functionality of * a token. * * ERC.20 Token standard: https://github.com/eth ereum/EIPs/issues/20 */ contract TokenInterface { // total amount of tokens uint totalSupply; /** * * balanceOf() - constant function check concrete tokens balance * * @param owner - account owner * * @return the value of balance */ function balanceOf(address owner) constant returns (uint256 balance); function transfer(address to, uint256 value) returns (bool success); function transferFrom(address from, address to, uint256 value) returns (bool success); /** * * approve() - function approves to a person to spend some tokens from * owner balance. * * @param spender - person whom this right been granted. * @param value - value to spend. * * @return true in case of succes, otherwise failure * */ function approve(address spender, uint256 value) returns (bool success); /** * * allowance() - constant function to check how much is * permitted to spend to 3rd person from owner balance * * @param owner - owner of the balance * @param spender - permitted to spend from this balance person * * @return - remaining right to spend * */ function allowance(address owner, address spender) constant returns (uint256 remaining); // events notifications event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /* * StandardToken - is a smart contract * for managing common functionality of * a token. * * ERC.20 Token standard: * https://github.com/eth ereum/EIPs/issues/20 */ contract StandardToken is TokenInterface { // token ownership mapping (address => uint256) balances; // spending permision management mapping (address => mapping (address => uint256)) allowed; function StandardToken(){ } /** * transfer() - transfer tokens from msg.sender balance * to requested account * * @param to - target address to transfer tokens * @param value - ammount of tokens to transfer * * @return - success / failure of the transaction */ function transfer(address to, uint256 value) returns (bool success) { if (balances[msg.sender] >= value && value > 0) { // do actual tokens transfer balances[msg.sender] -= value; balances[to] += value; // rise the Transfer event Transfer(msg.sender, to, value); return true; } else { return false; } } /** * transferFrom() - * * @param from - * @param to - * @param value - * * @return */ function transferFrom(address from, address to, uint256 value) returns (bool success) { if ( balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) { // do the actual transfer balances[from] -= value; balances[to] =+ value; // addjust the permision, after part of // permited to spend value was used allowed[from][msg.sender] -= value; // rise the Transfer event Transfer(from, to, value); return true; } else { return false; } } /** * * balanceOf() - constant function check concrete tokens balance * * @param owner - account owner * * @return the value of balance */ function balanceOf(address owner) constant returns (uint256 balance) { return balances[owner]; } /** * * approve() - function approves to a person to spend some tokens from * owner balance. * * @param spender - person whom this right been granted. * @param value - value to spend. * * @return true in case of succes, otherwise failure * */ function approve(address spender, uint256 value) returns (bool success) { // now spender can use balance in // ammount of value from owner balance allowed[msg.sender][spender] = value; // rise event about the transaction Approval(msg.sender, spender, value); return true; } /** * * allowance() - constant function to check how mouch is * permited to spend to 3rd person from owner balance * * @param owner - owner of the balance * @param spender - permited to spend from this balance person * * @return - remaining right to spend * */ function allowance(address owner, address spender) constant returns (uint256 remaining) { return allowed[owner][spender]; } } /** * * @title Hacker Gold * * The official token powering the hack.ether.camp virtual accelerator. * This is the only way to acquire tokens from startups during the event. * * Whitepaper https://hack.ether.camp/whitepaper * */ contract HackerGold is StandardToken { // Name of the token string public name = "HackerGold"; // Decimal places uint8 public decimals = 3; // Token abbreviation string public symbol = "HKG"; // 1 ether = 200 hkg uint BASE_PRICE = 200; // 1 ether = 150 hkg uint MID_PRICE = 150; // 1 ether = 100 hkg uint FIN_PRICE = 100; // Safety cap uint SAFETY_LIMIT = 4000000 ether; // Zeros after the point uint DECIMAL_ZEROS = 1000; // Total value in wei uint totalValue; // Address of multisig wallet holding ether from sale address wallet; // Structure of sale increase milestones struct milestones_struct { uint p1; uint p2; uint p3; uint p4; uint p5; uint p6; } // Milestones instance milestones_struct milestones; /** * Constructor of the contract. * * Passes address of the account holding the value. * HackerGold contract itself does not hold any value * * @param multisig address of MultiSig wallet which will hold the value */ function HackerGold(address multisig) { wallet = multisig; // set time periods for sale milestones = milestones_struct( 1476972000, // P1: GMT: 20-Oct-2016 14:00 => The Sale Starts 1478181600, // P2: GMT: 03-Nov-2016 14:00 => 1st Price Ladder 1479391200, // P3: GMT: 17-Nov-2016 14:00 => Price Stable, // Hackathon Starts 1480600800, // P4: GMT: 01-Dec-2016 14:00 => 2nd Price Ladder 1481810400, // P5: GMT: 15-Dec-2016 14:00 => Price Stable 1482415200 // P6: GMT: 22-Dec-2016 14:00 => Sale Ends, Hackathon Ends ); } /** * Fallback function: called on ether sent. * * It calls to createHKG function with msg.sender * as a value for holder argument */ function () payable { createHKG(msg.sender); } /** * Creates HKG tokens. * * Runs sanity checks including safety cap * Then calculates current price by getPrice() function, creates HKG tokens * Finally sends a value of transaction to the wallet * * Note: due to lack of floating point types in Solidity, * contract assumes that last 3 digits in tokens amount are stood after the point. * It means that if stored HKG balance is 100000, then its real value is 100 HKG * * @param holder token holder */ function createHKG(address holder) payable { if (now < milestones.p1) throw; if (now >= milestones.p6) throw; if (msg.value == 0) throw; // safety cap if (getTotalValue() + msg.value > SAFETY_LIMIT) throw; uint tokens = msg.value * getPrice() * DECIMAL_ZEROS / 1 ether; totalSupply += tokens; balances[holder] += tokens; totalValue += msg.value; if (!wallet.send(msg.value)) throw; } /** * Denotes complete price structure during the sale. * * @return HKG amount per 1 ETH for the current moment in time */ function getPrice() constant returns (uint result) { if (now < milestones.p1) return 0; if (now >= milestones.p1 && now < milestones.p2) { return BASE_PRICE; } if (now >= milestones.p2 && now < milestones.p3) { uint days_in = 1 + (now - milestones.p2) / 1 days; return BASE_PRICE - days_in * 25 / 7; // daily decrease 3.5 } if (now >= milestones.p3 && now < milestones.p4) { return MID_PRICE; } if (now >= milestones.p4 && now < milestones.p5) { days_in = 1 + (now - milestones.p4) / 1 days; return MID_PRICE - days_in * 25 / 7; // daily decrease 3.5 } if (now >= milestones.p5 && now < milestones.p6) { return FIN_PRICE; } if (now >= milestones.p6){ return 0; } } /** * Returns total stored HKG amount. * * Contract assumes that last 3 digits of this value are behind the decimal place. i.e. 10001 is 10.001 * Thus, result of this function should be divided by 1000 to get HKG value * * @return result stored HKG amount */ function getTotalSupply() constant returns (uint result) { return totalSupply; } /** * It is used for test purposes. * * Returns the result of 'now' statement of Solidity language * * @return unix timestamp for current moment in time */ function getNow() constant returns (uint result) { return now; } /** * Returns total value passed through the contract * * @return result total value in wei */ function getTotalValue() constant returns (uint result) { return totalValue; } } /** * * EventInfo - imutable class that denotes * the time of the virtual accelerator hack * event * */ contract EventInfo{ uint constant HACKATHON_5_WEEKS = 60 * 60 * 24 * 7 * 5; uint constant T_1_WEEK = 60 * 60 * 24 * 7; uint eventStart = 1479391200; // Thu, 17 Nov 2016 14:00:00 GMT uint eventEnd = eventStart + HACKATHON_5_WEEKS; /** * getEventStart - return the start of the event time */ function getEventStart() constant returns (uint result){ return eventStart; } /** * getEventEnd - return the end of the event time */ function getEventEnd() constant returns (uint result){ return eventEnd; } /** * getVotingStart - the voting starts 1 week after the * event starts */ function getVotingStart() constant returns (uint result){ return eventStart+ T_1_WEEK; } /** * getTradingStart - the DST tokens trading starts 1 week * after the event starts */ function getTradingStart() constant returns (uint result){ return eventStart+ T_1_WEEK; } /** * getNow - helper class to check what time the contract see */ function getNow() constant returns (uint result){ return now; } } /* * DSTContract - DST stands for decentralized startup team. * the contract ensures funding for a decentralized * team in 2 phases: * * +. Funding by HKG during the hackathon event. * +. Funding by Ether after the event is over. * * After the funds been collected there is a governence * mechanism managed by proposition to withdraw funds * for development usage. * * The DST ensures that backers of the projects keeps * some influence on the project by ability to reject * propositions they find as non effective. * * In very radical occasions the backers may loose * the trust in the team completelly, in that case * there is an option to propose impeachment process * completelly removing the execute and assigning new * person to manage the funds. * */ contract DSTContract is StandardToken{ // Zeros after the point uint DECIMAL_ZEROS = 1000; // Proposal lifetime uint PROPOSAL_LIFETIME = 10 days; // Proposal funds threshold, in percents uint PROPOSAL_FUNDS_TH = 20; address executive; EventInfo eventInfo; // Indicated where the DST is traded address virtualExchangeAddress; HackerGold hackerGold; mapping (address => uint256) votingRights; // 1 - HKG => DST qty; tokens for 1 HKG uint hkgPrice; // 1 - Ether => DST qty; tokens for 1 Ether uint etherPrice; string public name = "..."; uint8 public decimals = 3; string public symbol = "..."; bool ableToIssueTokens = true; uint preferedQtySold; uint collectedHKG; uint collectedEther; // Proposal of the funds spending mapping (bytes32 => Proposal) proposals; enum ProposalCurrency { HKG, ETHER } ProposalCurrency enumDeclaration; struct Proposal{ bytes32 id; uint value; string urlDetails; uint votindEndTS; uint votesObjecting; address submitter; bool redeemed; ProposalCurrency proposalCurrency; mapping (address => bool) voted; } uint counterProposals; uint timeOfLastProposal; Proposal[] listProposals; /** * Impeachment process proposals */ struct ImpeachmentProposal{ string urlDetails; address newExecutive; uint votindEndTS; uint votesSupporting; mapping (address => bool) voted; } ImpeachmentProposal lastImpeachmentProposal; /** * * DSTContract: ctor for DST token and governence contract * * @param eventInfoAddr EventInfo: address of object denotes events * milestones * @param hackerGoldAddr HackerGold: address of HackerGold token * * @param dstName string: dstName: real name of the team * * @param dstSymbol string: 3 letter symbold of the team * */ function DSTContract(EventInfo eventInfoAddr, HackerGold hackerGoldAddr, string dstName, string dstSymbol){ executive = msg.sender; name = dstName; symbol = dstSymbol; hackerGold = HackerGold(hackerGoldAddr); eventInfo = EventInfo(eventInfoAddr); } function() payable onlyAfterEnd { // there is tokens left from hackathon if (etherPrice == 0) throw; uint tokens = msg.value * etherPrice * DECIMAL_ZEROS / (1 ether); // check if demand of tokens is // overflow the supply uint retEther = 0; if (balances[this] < tokens) { tokens = balances[this]; retEther = msg.value - tokens / etherPrice * (1 finney); // return left ether if (!msg.sender.send(retEther)) throw; } // do transfer balances[msg.sender] += tokens; balances[this] -= tokens; // count collected ether collectedEther += msg.value - retEther; // rise event BuyForEtherTransaction(msg.sender, collectedEther, totalSupply, etherPrice, tokens); } /** * setHKGPrice - set price: 1HKG => DST tokens qty * * @param qtyForOneHKG uint: DST tokens for 1 HKG * */ function setHKGPrice(uint qtyForOneHKG) onlyExecutive { hkgPrice = qtyForOneHKG; PriceHKGChange(qtyForOneHKG, preferedQtySold, totalSupply); } /** * * issuePreferedTokens - prefered tokens issued on the hackathon event * grant special rights * * @param qtyForOneHKG uint: price DST tokens for one 1 HKG * @param qtyToEmit uint: new supply of tokens * */ function issuePreferedTokens(uint qtyForOneHKG, uint qtyToEmit) onlyExecutive onlyIfAbleToIssueTokens onlyBeforeEnd onlyAfterTradingStart { // no issuence is allowed before enlisted on the // exchange if (virtualExchangeAddress == 0x0) throw; totalSupply += qtyToEmit; balances[this] += qtyToEmit; hkgPrice = qtyForOneHKG; // now spender can use balance in // amount of value from owner balance allowed[this][virtualExchangeAddress] += qtyToEmit; // rise event about the transaction Approval(this, virtualExchangeAddress, qtyToEmit); // rise event DstTokensIssued(hkgPrice, preferedQtySold, totalSupply, qtyToEmit); } /** * * buyForHackerGold - on the hack event this function is available * the buyer for hacker gold will gain votes to * influence future proposals on the DST * * @param hkgValue - qty of this DST tokens for 1 HKG * */ function buyForHackerGold(uint hkgValue) onlyBeforeEnd returns (bool success) { // validate that the caller is official accelerator HKG Exchange if (msg.sender != virtualExchangeAddress) throw; // transfer token address sender = tx.origin; uint tokensQty = hkgValue * hkgPrice; // gain voting rights votingRights[sender] +=tokensQty; preferedQtySold += tokensQty; collectedHKG += hkgValue; // do actual transfer transferFrom(this, virtualExchangeAddress, tokensQty); transfer(sender, tokensQty); // rise event BuyForHKGTransaction(sender, preferedQtySold, totalSupply, hkgPrice, tokensQty); return true; } /** * * issueTokens - function will issue tokens after the * event, able to sell for 1 ether * * @param qtyForOneEther uint: DST tokens for 1 ETH * @param qtyToEmit uint: new tokens supply * */ function issueTokens(uint qtyForOneEther, uint qtyToEmit) onlyAfterEnd onlyExecutive onlyIfAbleToIssueTokens { balances[this] += qtyToEmit; etherPrice = qtyForOneEther; totalSupply += qtyToEmit; // rise event DstTokensIssued(qtyForOneEther, totalSupply, totalSupply, qtyToEmit); } /** * setEtherPrice - change the token price * * @param qtyForOneEther uint: new price - DST tokens for 1 ETH */ function setEtherPrice(uint qtyForOneEther) onlyAfterEnd onlyExecutive { etherPrice = qtyForOneEther; // rise event for this NewEtherPrice(qtyForOneEther); } /** * disableTokenIssuance - function will disable any * option for future token * issuence */ function disableTokenIssuance() onlyExecutive { ableToIssueTokens = false; DisableTokenIssuance(); } /** * burnRemainToken - eliminated all available for sale * tokens. */ function burnRemainToken() onlyExecutive { totalSupply -= balances[this]; balances[this] = 0; // rise event for this BurnedAllRemainedTokens(); } /** * submitEtherProposal: submit proposal to use part of the * collected ether funds * * @param requestValue uint: value in wei * @param url string: details of the proposal */ function submitEtherProposal(uint requestValue, string url) onlyAfterEnd onlyExecutive returns (bytes32 resultId, bool resultSucces) { // ensure there is no more issuence available if (ableToIssueTokens) throw; // ensure there is no more tokens available if (balanceOf(this) > 0) throw; // Possible to submit a proposal once 2 weeks if (now < (timeOfLastProposal + 2 weeks)) throw; uint percent = collectedEther / 100; if (requestValue > PROPOSAL_FUNDS_TH * percent) throw; // if remained value is less than requested gain all. if (requestValue > this.balance) requestValue = this.balance; // set id of the proposal // submit proposal to the map bytes32 id = sha3(msg.data, now); uint timeEnds = now + PROPOSAL_LIFETIME; Proposal memory newProposal = Proposal(id, requestValue, url, timeEnds, 0, msg.sender, false, ProposalCurrency.ETHER); proposals[id] = newProposal; listProposals.push(newProposal); timeOfLastProposal = now; ProposalRequestSubmitted(id, requestValue, timeEnds, url, msg.sender); return (id, true); } /** * * submitHKGProposal - submit proposal to request for * partial HKG funds collected * * @param requestValue uint: value in HKG to request. * @param url string: url with details on the proposition */ function submitHKGProposal(uint requestValue, string url) onlyAfterEnd onlyExecutive returns (bytes32 resultId, bool resultSucces){ // If there is no 2 months over since the last event. // There is no posible to get any HKG. After 2 months // all the HKG is available. if (now < (eventInfo.getEventEnd() + 8 weeks)) { throw; } // Possible to submit a proposal once 2 weeks if (now < (timeOfLastProposal + 2 weeks)) throw; uint percent = preferedQtySold / 100; // validate the amount is legit // first 5 proposals should be less than 20% if (counterProposals <= 5 && requestValue > PROPOSAL_FUNDS_TH * percent) throw; // if remained value is less than requested // gain all. if (requestValue > getHKGOwned()) requestValue = getHKGOwned(); // set id of the proposal // submit proposal to the map bytes32 id = sha3(msg.data, now); uint timeEnds = now + PROPOSAL_LIFETIME; Proposal memory newProposal = Proposal(id, requestValue, url, timeEnds, 0, msg.sender, false, ProposalCurrency.HKG); proposals[id] = newProposal; listProposals.push(newProposal); ++counterProposals; timeOfLastProposal = now; ProposalRequestSubmitted(id, requestValue, timeEnds, url, msg.sender); return (id, true); } /** * objectProposal - object previously submitted proposal, * the objection right is obtained by * purchasing prefered tokens on time of * the hackathon. * * @param id bytes32 : the id of the proposla to redeem */ function objectProposal(bytes32 id){ Proposal memory proposal = proposals[id]; // check proposal exist if (proposals[id].id == 0) throw; // check already redeemed if (proposals[id].redeemed) throw; // ensure objection time if (now >= proposals[id].votindEndTS) throw; // ensure not voted if (proposals[id].voted[msg.sender]) throw; // submit votes uint votes = votingRights[msg.sender]; proposals[id].votesObjecting += votes; // mark voted proposals[id].voted[msg.sender] = true; uint idx = getIndexByProposalId(id); listProposals[idx] = proposals[id]; ObjectedVote(id, msg.sender, votes); } function getIndexByProposalId(bytes32 id) returns (uint result){ for (uint i = 0; i < listProposals.length; ++i){ if (id == listProposals[i].id) return i; } } /** * redeemProposalFunds - redeem funds requested by prior * submitted proposal * * @param id bytes32: the id of the proposal to redeem */ function redeemProposalFunds(bytes32 id) onlyExecutive { if (proposals[id].id == 0) throw; if (proposals[id].submitter != msg.sender) throw; // ensure objection time if (now < proposals[id].votindEndTS) throw; // check already redeemed if (proposals[id].redeemed) throw; // check votes objection => 55% of total votes uint objectionThreshold = preferedQtySold / 100 * 55; if (proposals[id].votesObjecting > objectionThreshold) throw; if (proposals[id].proposalCurrency == ProposalCurrency.HKG){ // send hacker gold hackerGold.transfer(proposals[id].submitter, proposals[id].value); } else { // send ether bool success = proposals[id].submitter.send(proposals[id].value); // rise event EtherRedeemAccepted(proposals[id].submitter, proposals[id].value); } // execute the proposal proposals[id].redeemed = true; } /** * getAllTheFunds - to ensure there is no deadlock can * can happen, and no case that voting * structure will freeze the funds forever * the startup will be able to get all the * funds without a proposal required after * 6 months. * * */ function getAllTheFunds() onlyExecutive { // If there is a deadlock in voting participates // the funds can be redeemed completelly in 6 months if (now < (eventInfo.getEventEnd() + 24 weeks)) { throw; } // all the Ether bool success = msg.sender.send(this.balance); // all the HKG hackerGold.transfer(msg.sender, getHKGOwned()); } /** * submitImpeachmentProposal - submit request to switch * executive. * * @param urlDetails - details of the impeachment proposal * @param newExecutive - address of the new executive * */ function submitImpeachmentProposal(string urlDetails, address newExecutive){ // to offer impeachment you should have // voting rights if (votingRights[msg.sender] == 0) throw; // the submission of the first impeachment // proposal is possible only after 3 months // since the hackathon is over if (now < (eventInfo.getEventEnd() + 12 weeks)) throw; // check there is 1 months over since last one if (lastImpeachmentProposal.votindEndTS != 0 && lastImpeachmentProposal.votindEndTS + 2 weeks > now) throw; // submit impeachment proposal // add the votes of the submitter // to the proposal right away lastImpeachmentProposal = ImpeachmentProposal(urlDetails, newExecutive, now + 2 weeks, votingRights[msg.sender]); lastImpeachmentProposal.voted[msg.sender] = true; // rise event ImpeachmentProposed(msg.sender, urlDetails, now + 2 weeks, newExecutive); } /** * supportImpeachment - vote for impeachment proposal * that is currently in progress * */ function supportImpeachment(){ // ensure that support is for exist proposal if (lastImpeachmentProposal.newExecutive == 0x0) throw; // to offer impeachment you should have // voting rights if (votingRights[msg.sender] == 0) throw; // check if not voted already if (lastImpeachmentProposal.voted[msg.sender]) throw; // check if not finished the 2 weeks of voting if (lastImpeachmentProposal.votindEndTS + 2 weeks <= now) throw; // support the impeachment lastImpeachmentProposal.voted[msg.sender] = true; lastImpeachmentProposal.votesSupporting += votingRights[msg.sender]; // rise impeachment suppporting event ImpeachmentSupport(msg.sender, votingRights[msg.sender]); // if the vote is over 70% execute the switch uint percent = preferedQtySold / 100; if (lastImpeachmentProposal.votesSupporting >= 70 * percent){ executive = lastImpeachmentProposal.newExecutive; // impeachment event ImpeachmentAccepted(executive); } } // **************************** // // * Constant Getters * // // **************************** // function votingRightsOf(address _owner) constant returns (uint256 result) { result = votingRights[_owner]; } function getPreferedQtySold() constant returns (uint result){ return preferedQtySold; } function setVirtualExchange(address virtualExchangeAddr){ virtualExchangeAddress = virtualExchangeAddr; } function getHKGOwned() constant returns (uint result){ return hackerGold.balanceOf(this); } function getEtherValue() constant returns (uint result){ return this.balance; } function getExecutive() constant returns (address result){ return executive; } function getHKGPrice() constant returns (uint result){ return hkgPrice; } function getEtherPrice() constant returns (uint result){ return etherPrice; } function getDSTName() constant returns(string result){ return name; } function getDSTNameBytes() constant returns(bytes32 result){ return convert(name); } function getDSTSymbol() constant returns(string result){ return symbol; } function getDSTSymbolBytes() constant returns(bytes32 result){ return convert(symbol); } function getAddress() constant returns (address result) { return this; } function getTotalSupply() constant returns (uint result) { return totalSupply; } function getCollectedEther() constant returns (uint results) { return collectedEther; } function getCounterProposals() constant returns (uint result){ return counterProposals; } function getProposalIdByIndex(uint i) constant returns (bytes32 result){ return listProposals[i].id; } function getProposalObjectionByIndex(uint i) constant returns (uint result){ return listProposals[i].votesObjecting; } function getProposalValueByIndex(uint i) constant returns (uint result){ return listProposals[i].value; } function getCurrentImpeachmentUrlDetails() constant returns (string result){ return lastImpeachmentProposal.urlDetails; } function getCurrentImpeachmentVotesSupporting() constant returns (uint result){ return lastImpeachmentProposal.votesSupporting; } function convert(string key) returns (bytes32 ret) { if (bytes(key).length > 32) { throw; } assembly { ret := mload(add(key, 32)) } } // ********************* // // * Modifiers * // // ********************* // modifier onlyBeforeEnd() { if (now >= eventInfo.getEventEnd()) throw; _; } modifier onlyAfterEnd() { if (now < eventInfo.getEventEnd()) throw; _; } modifier onlyAfterTradingStart() { if (now < eventInfo.getTradingStart()) throw; _; } modifier onlyExecutive() { if (msg.sender != executive) throw; _; } modifier onlyIfAbleToIssueTokens() { if (!ableToIssueTokens) throw; _; } // ****************** // // * Events * // // ****************** // event PriceHKGChange(uint indexed qtyForOneHKG, uint indexed tokensSold, uint indexed totalSupply); event BuyForHKGTransaction(address indexed buyer, uint indexed tokensSold, uint indexed totalSupply, uint qtyForOneHKG, uint tokensAmount); event BuyForEtherTransaction(address indexed buyer, uint indexed tokensSold, uint indexed totalSupply, uint qtyForOneEther, uint tokensAmount); event DstTokensIssued(uint indexed qtyForOneHKG, uint indexed tokensSold, uint indexed totalSupply, uint qtyToEmit); event ProposalRequestSubmitted(bytes32 id, uint value, uint timeEnds, string url, address sender); event EtherRedeemAccepted(address sender, uint value); event ObjectedVote(bytes32 id, address voter, uint votes); event ImpeachmentProposed(address submitter, string urlDetails, uint votindEndTS, address newExecutive); event ImpeachmentSupport(address supportter, uint votes); event ImpeachmentAccepted(address newExecutive); event NewEtherPrice(uint newQtyForOneEther); event DisableTokenIssuance(); event BurnedAllRemainedTokens(); } /** * VirtualExchange - The exchange is a trading system used * on hack.ether.camp hackathon event to * support trading a DST tokens for HKG. * */ contract VirtualExchange{ address owner; EventInfo eventInfo; mapping (bytes32 => address) dstListed; HackerGold hackerGold; function VirtualExchange(address hackerGoldAddr, address eventInfoAddr){ owner = msg.sender; hackerGold = HackerGold(hackerGoldAddr); eventInfo = EventInfo(eventInfoAddr); } /** * enlist - enlisting one decentralized startup team to * the hack event virtual exchange, making the * DST initated tokens available for acquisition. * * @param dstAddress - address of the DSTContract * */ function enlist(address dstAddress) onlyBeforeEnd { DSTContract dstContract = DSTContract(dstAddress); bytes32 symbolBytes = dstContract.getDSTSymbolBytes(); /* Don't enlist 2 with the same name */ if (isExistByBytes(symbolBytes)) throw; // Only owner of the DST can deploy the DST if (dstContract.getExecutive() != msg.sender) throw; // All good enlist the company dstListed[symbolBytes] = dstAddress; // Indicate to DST which Virtual Exchange is enlisted dstContract.setVirtualExchange(address(this)); // rise Enlisted event Enlisted(dstAddress); } /** * * buy - on the hackathon timeframe that is the function * that will be the way to buy specific tokens for * startup. * * @param companyNameBytes - the company that is enlisted on the exchange * and the tokens are available * * @param hkg - the ammount of hkg to spend for aquastion * */ function buy(bytes32 companyNameBytes, uint hkg) onlyBeforeEnd returns (bool success) { // check DST exist if (!isExistByBytes(companyNameBytes)) throw; // validate availability DSTContract dstContract = DSTContract(dstListed[companyNameBytes]); uint tokensQty = hkg * dstContract.getHKGPrice(); address veAddress = address(this); // ensure that there is HKG balance uint valueHKGOwned = hackerGold.balanceOf(msg.sender); if (valueHKGOwned < hkg) throw; // ensure that there is HKG token allowed to be spend uint valueAvailbeOnExchange = hackerGold.allowance(msg.sender, veAddress); if (valueAvailbeOnExchange < hkg) throw; // ensure there is DST tokens for sale uint dstTokens = dstContract.allowance(dstContract, veAddress); if (dstTokens < hkg * dstContract.getHKGPrice()) throw; // Transfer HKG to Virtual Exchange account hackerGold.transferFrom(msg.sender, veAddress, hkg); // Transfer to dstCotract ownership hackerGold.transfer(dstContract.getAddress(), hkg); // Call DST to transfer tokens dstContract.buyForHackerGold(hkg); } // **************************** // // * Constant Getters * // // **************************** // function isExistByBytes(bytes32 companyNameBytes) constant returns (bool result) { if (dstListed[companyNameBytes] == 0x0) return false; else return true; } function getEventStart() constant eventInfoSet returns (uint result){ return eventInfo.getEventStart(); } function getEventEnd() constant eventInfoSet returns (uint result){ return eventInfo.getEventEnd(); } function getNow() constant returns (uint result){ return now; } // ********************* // // * Modifiers * // // ********************* // modifier onlyOwner() { if (msg.sender != owner) throw; _; } modifier eventInfoSet() { if (eventInfo == address(0)) throw; _; } modifier onlyBeforeEnd() { if (now >= eventInfo.getEventEnd()) throw; _; } modifier onlyAfterEnd() { if (now < eventInfo.getEventEnd()) throw; _; } // ****************** // // * Events * // // ****************** // event Enlisted(address indexed dstContract); }
issuePreferedTokens - prefered tokens issued on the hackathon event grant special rights qtyForOneHKG uint: price DST tokens for one 1 HKG qtyToEmit uint: new supply of tokens/ no issuence is allowed before enlisted on the exchange now spender can use balance in amount of value from owner balance rise event about the transaction rise event
function issuePreferedTokens(uint qtyForOneHKG, uint qtyToEmit) onlyExecutive onlyIfAbleToIssueTokens onlyBeforeEnd onlyAfterTradingStart { if (virtualExchangeAddress == 0x0) throw; totalSupply += qtyToEmit; balances[this] += qtyToEmit; hkgPrice = qtyForOneHKG; allowed[this][virtualExchangeAddress] += qtyToEmit; Approval(this, virtualExchangeAddress, qtyToEmit); DstTokensIssued(hkgPrice, preferedQtySold, totalSupply, qtyToEmit); }
940,532
./full_match/1/0x8FD2a943b681A80C5284e1eeB5a06B65e112f8e5/sources/contracts/SeaLife.sol
Adds new addresses to whitelist addresses address array/
function addToWhitelist(address[] calldata addresses) external onlyOwner { for(uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add NULL_ADDRESS to whitelist"); _whitelist[addresses[i]].isWhitelisted = true; } }
3,171,537
./full_match/1/0x6eaCC32119e988d0C1d16A1Dc493D01319998F94/sources/@tetu_io/tetu-contracts/contracts/base/governance/ControllableV2.sol
Filled only once when contract initialized _value block.number
function _setCreatedBlock(uint256 _value) private { bytes32 slot = _CREATED_BLOCK_SLOT; assembly { sstore(slot, _value) } }
2,939,256
./partial_match/56/0xF2A2D4071BC1F69EADb6763b13AFc2E406918bEE/sources/Exchange.sol
Fills the input order. order Order struct containing order specifications. takerAssetFillAmount Desired amount of takerAsset to sell. signature Proof that order has been created by maker. return Amounts filled and fees paid by maker and taker. Fetch order info Fetch taker address Assert that the order is fillable by taker Get amount of takerAsset to fill Validate context Compute proportional fill amounts Update exchange internal state Settle order
function fillOrderInternal( Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (FillResults memory fillResults) { OrderInfo memory orderInfo = getOrderInfo(order); address takerAddress = getCurrentContextAddress(); assertFillableOrder( order, orderInfo, takerAddress, signature ); uint256 remainingTakerAssetAmount = safeSub(order.takerAssetAmount, orderInfo.orderTakerAssetFilledAmount); uint256 takerAssetFilledAmount = min256(takerAssetFillAmount, remainingTakerAssetAmount); assertValidFill( order, orderInfo, takerAssetFillAmount, takerAssetFilledAmount, fillResults.makerAssetFilledAmount ); fillResults = calculateFillResults(order, takerAssetFilledAmount); updateFilledState( order, takerAddress, orderInfo.orderHash, orderInfo.orderTakerAssetFilledAmount, fillResults ); settleOrder( order, takerAddress, fillResults ); return fillResults; }
11,280,098
./full_match/42161/0xadb79a02839f4DA7Bdf37ed1e89177864c70B440/sources/ArbOtc.sol
Returns an array of trade offers within the specified range Pagination is used to fetch trade offers in smaller chunks startIndex The start index of the trade offers to fetch endIndex The end index of the trade offers to fetch return offers An array of TradeOffer structs within the specified range
function getOffers(uint256 startIndex, uint256 endIndex) public view returns (TradeOffer[] memory) { require(startIndex < endIndex, "Invalid range"); if(endIndex > tradeOffers.length) endIndex = tradeOffers.length; uint256 length = endIndex - startIndex; TradeOffer[] memory offers = new TradeOffer[](length); for (uint256 i = startIndex; i < endIndex; i++) { offers[i - startIndex] = tradeOffers[i]; } return offers; }
16,307,755
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** * @title Library for working with strings * @author yearn.finance */ library String { /** * @notice Search for a needle in a haystack * @param haystack The string to search * @param needle The string to search for */ function startsWith(string memory haystack, string memory needle) public pure returns (bool) { return indexOfStringInString(needle, haystack) == 0; } /** * @notice Find the index of a string in another string * @param needle The string to search for * @param haystack The string to search * @return Returns -1 if no match is found, otherwise returns the index of the match */ function indexOfStringInString(string memory needle, string memory haystack) public pure returns (int256) { bytes memory _needle = bytes(needle); bytes memory _haystack = bytes(haystack); if (_haystack.length < _needle.length) { return -1; } bool _match; for ( uint256 haystackIdx; haystackIdx < _haystack.length; haystackIdx++ ) { for (uint256 needleIdx; needleIdx < _needle.length; needleIdx++) { uint8 needleChar = uint8(_needle[needleIdx]); if (haystackIdx + needleIdx >= _haystack.length) { return -1; } uint8 haystackChar = uint8(_haystack[haystackIdx + needleIdx]); if (needleChar == haystackChar) { _match = true; if (needleIdx == _needle.length - 1) { return int256(haystackIdx); } } else { _match = false; break; } } } return -1; } /** * @notice Check to see if two strings are exactly equal * @dev Supports strings of arbitrary length * @param input0 First string to compare * @param input1 Second string to compare * @return Returns true if strings are exactly equal, false if not */ function equal(string memory input0, string memory input1) public pure returns (bool) { uint256 input0Length = bytes(input0).length; uint256 input1Length = bytes(input1).length; uint256 maxLength; if (input0Length > input1Length) { maxLength = input0Length; } else { maxLength = input1Length; } uint256 numberOfRowsToCompare = (maxLength / 32) + 1; bytes32 input0Bytes32; bytes32 input1Bytes32; for (uint256 rowIdx; rowIdx < numberOfRowsToCompare; rowIdx++) { uint256 offset = 0x20 * (rowIdx + 1); assembly { input0Bytes32 := mload(add(input0, offset)) input1Bytes32 := mload(add(input1, offset)) } if (input0Bytes32 != input1Bytes32) { return false; } } return true; } /** * @notice Convert ASCII to integer * @param input Integer as a string (ie. "345") * @param base Base to use for the conversion (10 for decimal) * @return output Returns uint256 representation of input string * @dev Based on GemERC721 utility but includes a fix */ function atoi(string memory input, uint8 base) public pure returns (uint256 output) { require(base == 2 || base == 8 || base == 10 || base == 16); bytes memory buf = bytes(input); for (uint256 idx = 0; idx < buf.length; idx++) { uint8 digit = uint8(buf[idx]) - 0x30; if (digit > 10) { digit -= 7; } require(digit < base); output *= base; output += digit; } return output; } /** * @notice Convert integer to ASCII * @param input Integer as a string (ie. "345") * @param base Base to use for the conversion (10 for decimal) * @return output Returns string representation of input integer * @dev Based on GemERC721 utility but includes a fix */ function itoa(uint256 input, uint8 base) public pure returns (string memory output) { require(base == 2 || base == 8 || base == 10 || base == 16); if (input == 0) { return "0"; } bytes memory buf = new bytes(256); uint256 idx = 0; while (input > 0) { uint8 digit = uint8(input % base); uint8 ascii = digit + 0x30; if (digit > 9) { ascii += 7; } buf[idx++] = bytes1(ascii); input /= base; } uint256 length = idx; for (idx = 0; idx < length / 2; idx++) { buf[idx] ^= buf[length - 1 - idx]; buf[length - 1 - idx] ^= buf[idx]; buf[idx] ^= buf[length - 1 - idx]; } output = string(buf); } /** * @notice Convert a string to lowercase * @param input Input string * @return Returns the string in lowercase */ function lowercase(string memory input) internal pure returns (string memory) { bytes memory _input = bytes(input); for (uint256 inputIdx = 0; inputIdx < _input.length; inputIdx++) { uint8 character = uint8(_input[inputIdx]); if (character >= 65 && character <= 90) { character += 0x20; _input[inputIdx] = bytes1(character); } } return string(_input); } /** * @notice Convert a string to uppercase * @param input Input string * @return Returns the string in uppercase */ function uppercase(string memory input) internal pure returns (string memory) { bytes memory _input = bytes(input); for (uint256 inputIdx = 0; inputIdx < _input.length; inputIdx++) { uint8 character = uint8(_input[inputIdx]); if (character >= 97 && character <= 122) { character -= 0x20; _input[inputIdx] = bytes1(character); } } return string(_input); } /** * @notice Determine whether or not haystack contains needle * @param haystack The string to search * @param needle The substring to search for * @return Returns true if needle exists in haystack, false if not */ function contains(string memory haystack, string memory needle) internal pure returns (bool) { return indexOfStringInString(needle, haystack) >= 0; } /** * @notice Convert bytes32 to string and remove padding * @param _bytes32 The input bytes32 data to convert * @return Returns the string representation of the bytes32 data */ function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while (i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } } contract Ownable { address public ownerAddress; constructor() { ownerAddress = msg.sender; } modifier onlyOwner() { require(msg.sender == ownerAddress, "Ownable: caller is not the owner"); _; } function setOwnerAddress(address _ownerAddress) public onlyOwner { ownerAddress = _ownerAddress; } } contract AddressesProvider is Ownable { mapping(uint256 => address) addressMap; mapping(uint256 => string) addressIdMap; uint256 addressesLength; struct AddressMetadata { string addrId; address addr; } function setAddress(AddressMetadata memory addressMetadata) public onlyOwner { string memory addressId = addressMetadata.addrId; address addr = addressMetadata.addr; uint256 upsertPosition = addressesLength; int256 addressPosition = addressPositionById(addressId); if (addressPosition >= 0) { upsertPosition = uint256(addressPosition); } else { addressIdMap[upsertPosition] = addressId; addressesLength++; } addressMap[upsertPosition] = addr; } function setAddresses(AddressMetadata[] memory _addressesMetadata) public onlyOwner { for ( uint256 addressMetadataIdx; addressMetadataIdx < _addressesMetadata.length; addressMetadataIdx++ ) { AddressMetadata memory addressMetadata = _addressesMetadata[ addressMetadataIdx ]; setAddress(addressMetadata); } } function addressPositionById(string memory addressId) public view returns (int256) { for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { string memory currentAddressId = addressIdMap[addressIdx]; if (String.equal(addressId, currentAddressId)) { return int256(addressIdx); } } return -1; } function addressById(string memory addressId) external view returns (address) { return addressMap[uint256(addressPositionById(addressId))]; } function addresses() external view returns (address[] memory) { address[] memory _addresses = new address[](addressesLength); for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { _addresses[addressIdx] = addressMap[addressIdx]; } return _addresses; } function addressesIds() external view returns (string[] memory) { string[] memory _addressesIds = new string[](addressesLength); for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { _addressesIds[addressIdx] = addressIdMap[addressIdx]; } return _addressesIds; } function addressesMetadata() external view returns (AddressMetadata[] memory) { AddressMetadata[] memory _addressesMetadata = new AddressMetadata[]( addressesLength ); for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { _addressesMetadata[addressIdx] = AddressMetadata({ addrId: addressIdMap[addressIdx], addr: addressMap[addressIdx] }); } return _addressesMetadata; } function addressesMetadataByIdStartsWith(string memory addressIdSubstring) external view returns (AddressMetadata[] memory) { AddressMetadata[] memory _addressesMetadata = new AddressMetadata[]( addressesLength ); uint256 _addressesLength; for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { string memory addressId = addressIdMap[addressIdx]; bool foundMatch = String.startsWith(addressId, addressIdSubstring); if (foundMatch) { _addressesMetadata[_addressesLength] = AddressMetadata({ addrId: addressIdMap[addressIdx], addr: addressMap[addressIdx] }); _addressesLength++; } } bytes memory encodedAddresses = abi.encode(_addressesMetadata); assembly { mstore(add(encodedAddresses, 0x40), _addressesLength) } AddressMetadata[] memory filteredAddresses = abi.decode( encodedAddresses, (AddressMetadata[]) ); return filteredAddresses; } }
Determine whether or not haystack contains needle haystack The string to search needle The substring to search for return Returns true if needle exists in haystack, false if not/
function contains(string memory haystack, string memory needle) internal pure returns (bool) { return indexOfStringInString(needle, haystack) >= 0; }
6,319,559
pragma solidity 0.5.12; interface IERC1820Implementer { function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32); } interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } interface IERC20 { function name() external view returns (string memory); // optional method - see eip spec function symbol() external view returns (string memory); // optional method - see eip spec function decimals() external view returns (uint8); // optional method - see eip spec function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function 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); } interface IERC777 { function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function balanceOf(address holder) external view returns (uint256); function granularity() external view returns (uint256); function defaultOperators() external view returns (address[] memory); function isOperatorFor( address operator, address holder ) external view returns (bool); function authorizeOperator(address operator) external; function revokeOperator(address operator) external; function send(address to, uint256 amount, bytes calldata data) external; function operatorSend( address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; function burn(uint256 amount, bytes calldata data) external; function operatorBurn( address from, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted( address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Burned( address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData ); event AuthorizedOperator( address indexed operator, address indexed holder ); event RevokedOperator(address indexed operator, address indexed holder); } interface IERC777Recipient { function tokensReceived(address operator, address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData) external; } interface IERC777Sender { function tokensToSend(address operator, address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData) external; } library LBasicToken { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Sent(address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed holder); event RevokedOperator(address indexed operator, address indexed holder); // Universal address as defined in Registry Contract Address section of https://eips.ethereum.org/EIPS/eip-1820 IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); struct TokenState { uint256 totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) approvals; mapping(address => mapping(address => bool)) authorizedOperators; address[] defaultOperators; mapping(address => bool) defaultOperatorIsRevoked; } function init(TokenState storage _tokenState, uint8 _decimals, uint256 _initialSupply) external { _tokenState.defaultOperators.push(address(this)); _tokenState.totalSupply = _initialSupply.mul(10**uint256(_decimals)); _tokenState.balances[msg.sender] = _tokenState.totalSupply; ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } function transferFrom(TokenState storage _tokenState, address _from, address _to, uint256 _value) external { require(_tokenState.approvals[_from][msg.sender] >= _value, "Amount not approved"); _tokenState.approvals[_from][msg.sender] = _tokenState.approvals[_from][msg.sender].sub(_value); doSend(_tokenState, msg.sender, _from, _to, _value, "", "", false); } function approve(TokenState storage _tokenState, address _spender, uint256 _value) external { require(_spender != address(0), "Cannot approve to zero address"); _tokenState.approvals[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); } function authorizeOperator(TokenState storage _tokenState, address _operator) external { require(_operator != msg.sender, "Self cannot be operator"); if (_operator == address(this)) _tokenState.defaultOperatorIsRevoked[msg.sender] = false; else _tokenState.authorizedOperators[_operator][msg.sender] = true; emit AuthorizedOperator(_operator, msg.sender); } function revokeOperator(TokenState storage _tokenState, address _operator) external { require(_operator != msg.sender, "Self cannot be operator"); if (_operator == address(this)) _tokenState.defaultOperatorIsRevoked[msg.sender] = true; else _tokenState.authorizedOperators[_operator][msg.sender] = false; emit RevokedOperator(_operator, msg.sender); } function doMint(TokenState storage _tokenState, address _to, uint256 _amount) external { assert(_to != address(0)); _tokenState.totalSupply = _tokenState.totalSupply.add(_amount); _tokenState.balances[_to] = _tokenState.balances[_to].add(_amount); // From ERC777: The token contract MUST call the tokensReceived hook after updating the state. receiveHook(address(this), address(0), _to, _amount, "", "", true); emit Minted(address(this), _to, _amount, "", ""); emit Transfer(address(0), _to, _amount); } function doBurn(TokenState storage _tokenState, address _operator, address _from, uint256 _amount, bytes calldata _data, bytes calldata _operatorData) external { assert(_from != address(0)); // From ERC777: The token contract MUST call the tokensToSend hook before updating the state. sendHook(_operator, _from, address(0), _amount, _data, _operatorData); _tokenState.balances[_from] = _tokenState.balances[_from].sub(_amount); _tokenState.totalSupply = _tokenState.totalSupply.sub(_amount); emit Burned(_operator, _from, _amount, _data, _operatorData); emit Transfer(_from, address(0), _amount); } function doSend(TokenState storage _tokenState, address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _enforceERC777) public { assert(_from != address(0)); require(_to != address(0), "Zero address cannot receive funds"); // From ERC777: The token contract MUST call the tokensToSend hook before updating the state. sendHook(_operator, _from, _to, _amount, _data, _operatorData); _tokenState.balances[_from] = _tokenState.balances[_from].sub(_amount); _tokenState.balances[_to] = _tokenState.balances[_to].add(_amount); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); emit Transfer(_from, _to, _amount); // From ERC777: The token contract MUST call the tokensReceived hook after updating the state. receiveHook(_operator, _from, _to, _amount, _data, _operatorData, _enforceERC777); } function receiveHook(address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _enforceERC777) public { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(_to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) IERC777Recipient(implementer).tokensReceived(_operator, _from, _to, _amount, _data, _operatorData); else if (_enforceERC777) require(!isContract(_to), "Contract must be registered with ERC1820 as implementing ERC777TokensRecipient"); } function sendHook(address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData) public { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(_from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) IERC777Sender(implementer).tokensToSend(_operator, _from, _to, _amount, _data, _operatorData); } function isContract(address _account) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_account) } isContract_ = size != 0; } } contract Owned { address public owner = msg.sender; event LogOwnershipTransferred(address indexed owner, address indexed newOwner); modifier onlyOwner { require(msg.sender == owner, "Sender must be owner"); _; } function setOwner(address _owner) external onlyOwner { require(_owner != address(0), "Owner cannot be zero address"); emit LogOwnershipTransferred(owner, _owner); owner = _owner; } } contract PDelegate { /** * @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 memory _calldata) internal { assert(isContract(_dst)); assembly { let result := delegatecall(sub(gas, 10000), _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) } } } // ONLY_IF_ASSERTS_ON: function isContract(address _target) view internal returns (bool result_) { uint256 size; assembly { size := extcodesize(_target) } result_ = (size != 0); } // :ONLY_IF_ASSERTS_ON } 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; } } contract BasicToken is IERC777, IERC20, Owned, PDelegate { uint8 public constant decimals = 18; uint256 public constant granularity = 1; string public name; string public symbol; LBasicToken.TokenState private tokenState; address public extensionContract; // TODO: Move to tokenState? event LogContractExtended(address indexed extensionContract); constructor(string memory _name, string memory _symbol, uint256 _initialSupply) public { require(bytes(_name).length != 0, "Needs a name"); require(bytes(_symbol).length != 0, "Needs a symbol"); name = _name; symbol = _symbol; LBasicToken.init(tokenState, decimals, _initialSupply); } modifier onlyOperator(address _holder) { require(isOperatorFor(msg.sender, _holder), "Not an operator"); _; } // MUST be overriden by any extension contract to avoid recursion of delegateFwd calls. function () external { require(extensionContract != address(0), "Extended functionality contract not found"); delegatedFwd(extensionContract, msg.data); } function extend(address _extensionContract) external onlyOwner { extensionContract = _extensionContract; emit LogContractExtended(_extensionContract); } function balanceOf(address _holder) external view returns (uint256 balance_) { balance_ = tokenState.balances[_holder]; } function transfer(address _to, uint256 _value) external returns (bool success_) { doSend(msg.sender, msg.sender, _to, _value, "", "", false); success_ = true; } function transferFrom(address _from, address _to, uint256 _value) external returns (bool success_) { LBasicToken.transferFrom(tokenState, _from, _to, _value); success_ = true; } function approve(address _spender, uint256 _value) external returns (bool success_) { LBasicToken.approve(tokenState, _spender, _value); success_ = true; } function allowance(address _holder, address _spender) external view returns (uint256 remaining_) { remaining_ = tokenState.approvals[_holder][_spender]; } function defaultOperators() external view returns (address[] memory) { return tokenState.defaultOperators; } function authorizeOperator(address _operator) external { LBasicToken.authorizeOperator(tokenState, _operator); } function revokeOperator(address _operator) external { LBasicToken.revokeOperator(tokenState, _operator); } function send(address _to, uint256 _amount, bytes calldata _data) external { doSend(msg.sender, msg.sender, _to, _amount, _data, "", true); } function operatorSend(address _from, address _to, uint256 _amount, bytes calldata _data, bytes calldata _operatorData) external onlyOperator(_from) { doSend(msg.sender, _from, _to, _amount, _data, _operatorData, true); } function burn(uint256 _amount, bytes calldata _data) external { doBurn(msg.sender, msg.sender, _amount, _data, ""); } function operatorBurn(address _from, uint256 _amount, bytes calldata _data, bytes calldata _operatorData) external onlyOperator(_from) { doBurn(msg.sender, _from, _amount, _data, _operatorData); } function totalSupply() external view returns (uint256 totalSupply_) { totalSupply_ = tokenState.totalSupply; } function isOperatorFor(address _operator, address _holder) public view returns (bool isOperatorFor_) { isOperatorFor_ = (_operator == _holder || tokenState.authorizedOperators[_operator][_holder] || _operator == address(this) && !tokenState.defaultOperatorIsRevoked[_holder]); } function doSend(address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _enforceERC777) internal { LBasicToken.doSend(tokenState, _operator, _from, _to, _amount, _data, _operatorData, _enforceERC777); } function doMint(address _to, uint256 _amount) internal { LBasicToken.doMint(tokenState, _to, _amount); } function doBurn(address _operator, address _from, uint256 _amount, bytes memory _data, bytes memory _operatorData) internal { LBasicToken.doBurn(tokenState, _operator, _from, _amount, _data, _operatorData); } } contract VOWTokenPublic is BasicToken { mapping(address => bool) public vscContracts; event LogVSCContractRegistered(address indexed vscContract); event LogVSCContractDeregistered(address indexed vscContract); constructor(uint256 _initialSupply) BasicToken("Vow", "Vow", _initialSupply) public {} function registerVSCContract(address _vscContract) external onlyOwner { require(!vscContracts[_vscContract], "VSC contract already registered"); vscContracts[_vscContract] = true; emit LogVSCContractRegistered(_vscContract); } function deregisterVSCContract(address _vscContract) external onlyOwner { require(vscContracts[_vscContract], "VSC contract is not registered"); vscContracts[_vscContract] = false; emit LogVSCContractDeregistered(_vscContract); } function isRegisteredVSCContract(address _vscContract) public view returns (bool isRegistered_) { isRegistered_ = vscContracts[_vscContract]; } }
From ERC777: The token contract MUST call the tokensToSend hook before updating the state. From ERC777: The token contract MUST call the tokensReceived hook after updating the state.
function doSend(TokenState storage _tokenState, address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _enforceERC777) public { assert(_from != address(0)); require(_to != address(0), "Zero address cannot receive funds"); sendHook(_operator, _from, _to, _amount, _data, _operatorData); _tokenState.balances[_from] = _tokenState.balances[_from].sub(_amount); _tokenState.balances[_to] = _tokenState.balances[_to].add(_amount); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); emit Transfer(_from, _to, _amount); receiveHook(_operator, _from, _to, _amount, _data, _operatorData, _enforceERC777); }
7,524,905
./partial_match/3/0x4799bc9761f0da4E46B08468e69C9ba972935423/sources/YZYVault.sol
Return Treasury fee/
function treasuryFee() external view returns (uint16) { return _treasuryFee; }
5,052,580
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function LOG40(address p0, string memory p1) internal view {
1,018,893
pragma solidity ^0.4.25; contract IStdToken { 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); } contract EtheramaCommon { //main adrministrators of the Etherama network mapping(address => bool) private _administrators; //main managers of the Etherama network mapping(address => bool) private _managers; modifier onlyAdministrator() { require(_administrators[msg.sender]); _; } modifier onlyAdministratorOrManager() { require(_administrators[msg.sender] || _managers[msg.sender]); _; } constructor() public { _administrators[msg.sender] = true; } function addAdministator(address addr) onlyAdministrator public { _administrators[addr] = true; } function removeAdministator(address addr) onlyAdministrator public { _administrators[addr] = false; } function isAdministrator(address addr) public view returns (bool) { return _administrators[addr]; } function addManager(address addr) onlyAdministrator public { _managers[addr] = true; } function removeManager(address addr) onlyAdministrator public { _managers[addr] = false; } function isManager(address addr) public view returns (bool) { return _managers[addr]; } } contract EtheramaGasPriceLimit is EtheramaCommon { uint256 public MAX_GAS_PRICE = 0 wei; event onSetMaxGasPrice(uint256 val); //max gas price modifier for buy/sell transactions in order to avoid a "front runner" vulnerability. //It is applied to all network contracts modifier validGasPrice(uint256 val) { require(val > 0); _; } constructor(uint256 maxGasPrice) public validGasPrice(maxGasPrice) { setMaxGasPrice(maxGasPrice); } //only main administators or managers can set max gas price function setMaxGasPrice(uint256 val) public validGasPrice(val) onlyAdministratorOrManager { MAX_GAS_PRICE = val; emit onSetMaxGasPrice(val); } } // Core contract for Etherama network contract EtheramaCore is EtheramaGasPriceLimit { uint256 constant public MAGNITUDE = 2**64; // Max and min amount of tokens which can be bought or sold. There are such limits because of math precision uint256 constant public MIN_TOKEN_DEAL_VAL = 0.1 ether; uint256 constant public MAX_TOKEN_DEAL_VAL = 1000000 ether; // same same for ETH uint256 constant public MIN_ETH_DEAL_VAL = 0.001 ether; uint256 constant public MAX_ETH_DEAL_VAL = 200000 ether; // percent of a transaction commission which is taken for Big Promo bonus uint256 public _bigPromoPercent = 5 ether; // percent of a transaction commission which is taken for Quick Promo bonus uint256 public _quickPromoPercent = 5 ether; // percent of a transaction commission which is taken for Etherama DEV team uint256 public _devRewardPercent = 15 ether; // percent of a transaction commission which is taken for Token Owner. uint256 public _tokenOwnerRewardPercent = 30 ether; // percent of a transaction commission which is taken for share reward. Each token holder receives a small reward from each buy or sell transaction proportionally his holding. uint256 public _shareRewardPercent = 25 ether; // percent of a transaction commission which is taken for a feraral link owner. If there is no any referal then this part of commission goes to share reward. uint256 public _refBonusPercent = 20 ether; // interval of blocks for Big Promo bonus. It means that a user which buy a bunch of tokens for X ETH in that particular block will receive a special bonus uint128 public _bigPromoBlockInterval = 9999; // same same for Quick Promo uint128 public _quickPromoBlockInterval = 100; // minimum eth amount of a purchase which is required to participate in promo. uint256 public _promoMinPurchaseEth = 1 ether; // minimum eth purchase which is required to get a referal link. uint256 public _minRefEthPurchase = 0.5 ether; // percent of fee which is supposed to distribute. uint256 public _totalIncomeFeePercent = 100 ether; // current collected big promo bonus uint256 public _currentBigPromoBonus; // current collected quick promo bonus uint256 public _currentQuickPromoBonus; uint256 public _devReward; uint256 public _initBlockNum; mapping(address => bool) private _controllerContracts; mapping(uint256 => address) private _controllerIndexer; uint256 private _controllerContractCount; //user token balances per data contracts mapping(address => mapping(address => uint256)) private _userTokenLocalBalances; //user reward payouts per data contracts mapping(address => mapping(address => uint256)) private _rewardPayouts; //user ref rewards per data contracts mapping(address => mapping(address => uint256)) private _refBalances; //user won quick promo bonuses per data contracts mapping(address => mapping(address => uint256)) private _promoQuickBonuses; //user won big promo bonuses per data contracts mapping(address => mapping(address => uint256)) private _promoBigBonuses; //user saldo between buys and sels in eth per data contracts mapping(address => mapping(address => uint256)) private _userEthVolumeSaldos; //bonuses per share per data contracts mapping(address => uint256) private _bonusesPerShare; //buy counts per data contracts mapping(address => uint256) private _buyCounts; //sell counts per data contracts mapping(address => uint256) private _sellCounts; //total volume eth per data contracts mapping(address => uint256) private _totalVolumeEth; //total volume tokens per data contracts mapping(address => uint256) private _totalVolumeToken; event onWithdrawUserBonus(address indexed userAddress, uint256 ethWithdrawn); modifier onlyController() { require(_controllerContracts[msg.sender]); _; } constructor(uint256 maxGasPrice) EtheramaGasPriceLimit(maxGasPrice) public { _initBlockNum = block.number; } function getInitBlockNum() public view returns (uint256) { return _initBlockNum; } function addControllerContract(address addr) onlyAdministrator public { _controllerContracts[addr] = true; _controllerIndexer[_controllerContractCount] = addr; _controllerContractCount = SafeMath.add(_controllerContractCount, 1); } function removeControllerContract(address addr) onlyAdministrator public { _controllerContracts[addr] = false; } function changeControllerContract(address oldAddr, address newAddress) onlyAdministrator public { _controllerContracts[oldAddr] = false; _controllerContracts[newAddress] = true; } function setBigPromoInterval(uint128 val) onlyAdministrator public { _bigPromoBlockInterval = val; } function setQuickPromoInterval(uint128 val) onlyAdministrator public { _quickPromoBlockInterval = val; } function addBigPromoBonus() onlyController payable public { _currentBigPromoBonus = SafeMath.add(_currentBigPromoBonus, msg.value); } function addQuickPromoBonus() onlyController payable public { _currentQuickPromoBonus = SafeMath.add(_currentQuickPromoBonus, msg.value); } function setPromoMinPurchaseEth(uint256 val) onlyAdministrator public { _promoMinPurchaseEth = val; } function setMinRefEthPurchase(uint256 val) onlyAdministrator public { _minRefEthPurchase = val; } function setTotalIncomeFeePercent(uint256 val) onlyController public { require(val > 0 && val <= 100 ether); _totalIncomeFeePercent = val; } // set reward persentages of buy/sell fee. Token owner cannot take more than 40%. function setRewardPercentages(uint256 tokenOwnerRewardPercent, uint256 shareRewardPercent, uint256 refBonusPercent, uint256 bigPromoPercent, uint256 quickPromoPercent) onlyAdministrator public { require(tokenOwnerRewardPercent <= 40 ether); require(shareRewardPercent <= 100 ether); require(refBonusPercent <= 100 ether); require(bigPromoPercent <= 100 ether); require(quickPromoPercent <= 100 ether); require(tokenOwnerRewardPercent + shareRewardPercent + refBonusPercent + _devRewardPercent + _bigPromoPercent + _quickPromoPercent == 100 ether); _tokenOwnerRewardPercent = tokenOwnerRewardPercent; _shareRewardPercent = shareRewardPercent; _refBonusPercent = refBonusPercent; _bigPromoPercent = bigPromoPercent; _quickPromoPercent = quickPromoPercent; } function payoutQuickBonus(address userAddress) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _promoQuickBonuses[dataContractAddress][userAddress] = SafeMath.add(_promoQuickBonuses[dataContractAddress][userAddress], _currentQuickPromoBonus); _currentQuickPromoBonus = 0; } function payoutBigBonus(address userAddress) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _promoBigBonuses[dataContractAddress][userAddress] = SafeMath.add(_promoBigBonuses[dataContractAddress][userAddress], _currentBigPromoBonus); _currentBigPromoBonus = 0; } function addDevReward() onlyController payable public { _devReward = SafeMath.add(_devReward, msg.value); } function withdrawDevReward() onlyAdministrator public { uint256 reward = _devReward; _devReward = 0; msg.sender.transfer(reward); } function getBlockNumSinceInit() public view returns(uint256) { return block.number - getInitBlockNum(); } function getQuickPromoRemainingBlocks() public view returns(uint256) { uint256 d = getBlockNumSinceInit() % _quickPromoBlockInterval; d = d == 0 ? _quickPromoBlockInterval : d; return _quickPromoBlockInterval - d; } function getBigPromoRemainingBlocks() public view returns(uint256) { uint256 d = getBlockNumSinceInit() % _bigPromoBlockInterval; d = d == 0 ? _bigPromoBlockInterval : d; return _bigPromoBlockInterval - d; } function getBonusPerShare(address dataContractAddress) public view returns(uint256) { return _bonusesPerShare[dataContractAddress]; } function getTotalBonusPerShare() public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _bonusesPerShare[Etherama(_controllerIndexer[i]).getDataContractAddress()]); } } function addBonusPerShare() onlyController payable public { EtheramaData data = Etherama(msg.sender)._data(); uint256 shareBonus = (msg.value * MAGNITUDE) / data.getTotalTokenSold(); _bonusesPerShare[address(data)] = SafeMath.add(_bonusesPerShare[address(data)], shareBonus); } function getUserRefBalance(address dataContractAddress, address userAddress) public view returns(uint256) { return _refBalances[dataContractAddress][userAddress]; } function getUserRewardPayouts(address dataContractAddress, address userAddress) public view returns(uint256) { return _rewardPayouts[dataContractAddress][userAddress]; } function resetUserRefBalance(address userAddress) onlyController public { resetUserRefBalance(Etherama(msg.sender).getDataContractAddress(), userAddress); } function resetUserRefBalance(address dataContractAddress, address userAddress) internal { _refBalances[dataContractAddress][userAddress] = 0; } function addUserRefBalance(address userAddress) onlyController payable public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _refBalances[dataContractAddress][userAddress] = SafeMath.add(_refBalances[dataContractAddress][userAddress], msg.value); } function addUserRewardPayouts(address userAddress, uint256 val) onlyController public { addUserRewardPayouts(Etherama(msg.sender).getDataContractAddress(), userAddress, val); } function addUserRewardPayouts(address dataContractAddress, address userAddress, uint256 val) internal { _rewardPayouts[dataContractAddress][userAddress] = SafeMath.add(_rewardPayouts[dataContractAddress][userAddress], val); } function resetUserPromoBonus(address userAddress) onlyController public { resetUserPromoBonus(Etherama(msg.sender).getDataContractAddress(), userAddress); } function resetUserPromoBonus(address dataContractAddress, address userAddress) internal { _promoQuickBonuses[dataContractAddress][userAddress] = 0; _promoBigBonuses[dataContractAddress][userAddress] = 0; } function trackBuy(address userAddress, uint256 volEth, uint256 volToken) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _buyCounts[dataContractAddress] = SafeMath.add(_buyCounts[dataContractAddress], 1); _userEthVolumeSaldos[dataContractAddress][userAddress] = SafeMath.add(_userEthVolumeSaldos[dataContractAddress][userAddress], volEth); trackTotalVolume(dataContractAddress, volEth, volToken); } function trackSell(address userAddress, uint256 volEth, uint256 volToken) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _sellCounts[dataContractAddress] = SafeMath.add(_sellCounts[dataContractAddress], 1); _userEthVolumeSaldos[dataContractAddress][userAddress] = SafeMath.sub(_userEthVolumeSaldos[dataContractAddress][userAddress], volEth); trackTotalVolume(dataContractAddress, volEth, volToken); } function trackTotalVolume(address dataContractAddress, uint256 volEth, uint256 volToken) internal { _totalVolumeEth[dataContractAddress] = SafeMath.add(_totalVolumeEth[dataContractAddress], volEth); _totalVolumeToken[dataContractAddress] = SafeMath.add(_totalVolumeToken[dataContractAddress], volToken); } function getBuyCount(address dataContractAddress) public view returns (uint256) { return _buyCounts[dataContractAddress]; } function getTotalBuyCount() public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _buyCounts[Etherama(_controllerIndexer[i]).getDataContractAddress()]); } } function getSellCount(address dataContractAddress) public view returns (uint256) { return _sellCounts[dataContractAddress]; } function getTotalSellCount() public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _sellCounts[Etherama(_controllerIndexer[i]).getDataContractAddress()]); } } function getTotalVolumeEth(address dataContractAddress) public view returns (uint256) { return _totalVolumeEth[dataContractAddress]; } function getTotalVolumeToken(address dataContractAddress) public view returns (uint256) { return _totalVolumeToken[dataContractAddress]; } function getUserEthVolumeSaldo(address dataContractAddress, address userAddress) public view returns (uint256) { return _userEthVolumeSaldos[dataContractAddress][userAddress]; } function getUserTotalEthVolumeSaldo(address userAddress) public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _userEthVolumeSaldos[Etherama(_controllerIndexer[i]).getDataContractAddress()][userAddress]); } } function getTotalCollectedPromoBonus() public view returns (uint256) { return SafeMath.add(_currentBigPromoBonus, _currentQuickPromoBonus); } function getUserTotalPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) { return SafeMath.add(_promoQuickBonuses[dataContractAddress][userAddress], _promoBigBonuses[dataContractAddress][userAddress]); } function getUserQuickPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) { return _promoQuickBonuses[dataContractAddress][userAddress]; } function getUserBigPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) { return _promoBigBonuses[dataContractAddress][userAddress]; } function getUserTokenLocalBalance(address dataContractAddress, address userAddress) public view returns(uint256) { return _userTokenLocalBalances[dataContractAddress][userAddress]; } function addUserTokenLocalBalance(address userAddress, uint256 val) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _userTokenLocalBalances[dataContractAddress][userAddress] = SafeMath.add(_userTokenLocalBalances[dataContractAddress][userAddress], val); } function subUserTokenLocalBalance(address userAddress, uint256 val) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _userTokenLocalBalances[dataContractAddress][userAddress] = SafeMath.sub(_userTokenLocalBalances[dataContractAddress][userAddress], val); } function getUserReward(address dataContractAddress, address userAddress, bool incShareBonus, bool incRefBonus, bool incPromoBonus) public view returns(uint256 reward) { EtheramaData data = EtheramaData(dataContractAddress); if (incShareBonus) { reward = data.getBonusPerShare() * data.getActualUserTokenBalance(userAddress); reward = ((reward < data.getUserRewardPayouts(userAddress)) ? 0 : SafeMath.sub(reward, data.getUserRewardPayouts(userAddress))) / MAGNITUDE; } if (incRefBonus) reward = SafeMath.add(reward, data.getUserRefBalance(userAddress)); if (incPromoBonus) reward = SafeMath.add(reward, data.getUserTotalPromoBonus(userAddress)); return reward; } //user's total reward from all the tokens on the table. includes share reward + referal bonus + promo bonus function getUserTotalReward(address userAddress, bool incShareBonus, bool incRefBonus, bool incPromoBonus) public view returns(uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { address dataContractAddress = Etherama(_controllerIndexer[i]).getDataContractAddress(); res = SafeMath.add(res, getUserReward(dataContractAddress, userAddress, incShareBonus, incRefBonus, incPromoBonus)); } } //current user's reward function getCurrentUserReward(bool incRefBonus, bool incPromoBonus) public view returns(uint256) { return getUserTotalReward(msg.sender, true, incRefBonus, incPromoBonus); } //current user's total reward from all the tokens on the table function getCurrentUserTotalReward() public view returns(uint256) { return getUserTotalReward(msg.sender, true, true, true); } //user's share bonus from all the tokens on the table function getCurrentUserShareBonus() public view returns(uint256) { return getUserTotalReward(msg.sender, true, false, false); } //current user's ref bonus from all the tokens on the table function getCurrentUserRefBonus() public view returns(uint256) { return getUserTotalReward(msg.sender, false, true, false); } //current user's promo bonus from all the tokens on the table function getCurrentUserPromoBonus() public view returns(uint256) { return getUserTotalReward(msg.sender, false, false, true); } //is ref link available for the user function isRefAvailable(address refAddress) public view returns(bool) { return getUserTotalEthVolumeSaldo(refAddress) >= _minRefEthPurchase; } //is ref link available for the current user function isRefAvailable() public view returns(bool) { return isRefAvailable(msg.sender); } //Withdraws all of the user earnings. function withdrawUserReward() public { uint256 reward = getRewardAndPrepareWithdraw(); require(reward > 0); msg.sender.transfer(reward); emit onWithdrawUserBonus(msg.sender, reward); } //gather all the user's reward and prepare it to withdaw function getRewardAndPrepareWithdraw() internal returns(uint256 reward) { for (uint256 i = 0; i < _controllerContractCount; i++) { address dataContractAddress = Etherama(_controllerIndexer[i]).getDataContractAddress(); reward = SafeMath.add(reward, getUserReward(dataContractAddress, msg.sender, true, false, false)); // add share reward to payouts addUserRewardPayouts(dataContractAddress, msg.sender, reward * MAGNITUDE); // add ref bonus reward = SafeMath.add(reward, getUserRefBalance(dataContractAddress, msg.sender)); resetUserRefBalance(dataContractAddress, msg.sender); // add promo bonus reward = SafeMath.add(reward, getUserTotalPromoBonus(dataContractAddress, msg.sender)); resetUserPromoBonus(dataContractAddress, msg.sender); } return reward; } //withdaw all the remamining ETH if there is no one active contract. We don't want to leave them here forever function withdrawRemainingEthAfterAll() onlyAdministrator public { for (uint256 i = 0; i < _controllerContractCount; i++) { if (Etherama(_controllerIndexer[i]).isActive()) revert(); } msg.sender.transfer(address(this).balance); } function calcPercent(uint256 amount, uint256 percent) public pure returns(uint256) { return SafeMath.div(SafeMath.mul(SafeMath.div(amount, 100), percent), 1 ether); } //Converts real num to uint256. Works only with positive numbers. function convertRealTo256(int128 realVal) public pure returns(uint256) { int128 roundedVal = RealMath.fromReal(RealMath.mul(realVal, RealMath.toReal(1e12))); return SafeMath.mul(uint256(roundedVal), uint256(1e6)); } //Converts uint256 to real num. Possible a little loose of precision function convert256ToReal(uint256 val) public pure returns(int128) { uint256 intVal = SafeMath.div(val, 1e6); require(RealMath.isUInt256ValidIn64(intVal)); return RealMath.fraction(int64(intVal), 1e12); } } // Data contract for Etherama contract controller. Data contract cannot be changed so no data can be lost. On the other hand Etherama controller can be replaced if some error is found. contract EtheramaData { // tranding token address address constant public TOKEN_CONTRACT_ADDRESS = 0x83cee9e086A77e492eE0bB93C2B0437aD6fdECCc; // token price in the begining uint256 constant public TOKEN_PRICE_INITIAL = 0.0023 ether; // a percent of the token price which adds/subs each _priceSpeedInterval tokens uint64 constant public PRICE_SPEED_PERCENT = 5; // Token price speed interval. For instance, if PRICE_SPEED_PERCENT = 5 and PRICE_SPEED_INTERVAL = 10000 it means that after 10000 tokens are bought/sold token price will increase/decrease for 5%. uint64 constant public PRICE_SPEED_INTERVAL = 10000; // lock-up period in days. Until this period is expeired nobody can close the contract or withdraw users' funds uint64 constant public EXP_PERIOD_DAYS = 365; mapping(address => bool) private _administrators; uint256 private _administratorCount; uint64 public _initTime; uint64 public _expirationTime; uint256 public _tokenOwnerReward; uint256 public _totalSupply; int128 public _realTokenPrice; address public _controllerAddress = address(0x0); EtheramaCore public _core; uint256 public _initBlockNum; bool public _hasMaxPurchaseLimit = false; IStdToken public _token; //only main contract modifier onlyController() { require(msg.sender == _controllerAddress); _; } constructor(address coreAddress) public { require(coreAddress != address(0x0)); _core = EtheramaCore(coreAddress); _initBlockNum = block.number; } function init() public { require(_controllerAddress == address(0x0)); require(TOKEN_CONTRACT_ADDRESS != address(0x0)); require(RealMath.isUInt64ValidIn64(PRICE_SPEED_PERCENT) && PRICE_SPEED_PERCENT > 0); require(RealMath.isUInt64ValidIn64(PRICE_SPEED_INTERVAL) && PRICE_SPEED_INTERVAL > 0); _controllerAddress = msg.sender; _token = IStdToken(TOKEN_CONTRACT_ADDRESS); _initTime = uint64(now); _expirationTime = _initTime + EXP_PERIOD_DAYS * 1 days; _realTokenPrice = _core.convert256ToReal(TOKEN_PRICE_INITIAL); } function isInited() public view returns(bool) { return (_controllerAddress != address(0x0)); } function getCoreAddress() public view returns(address) { return address(_core); } function setNewControllerAddress(address newAddress) onlyController public { _controllerAddress = newAddress; } function getPromoMinPurchaseEth() public view returns(uint256) { return _core._promoMinPurchaseEth(); } function addAdministator(address addr) onlyController public { _administrators[addr] = true; _administratorCount = SafeMath.add(_administratorCount, 1); } function removeAdministator(address addr) onlyController public { _administrators[addr] = false; _administratorCount = SafeMath.sub(_administratorCount, 1); } function getAdministratorCount() public view returns(uint256) { return _administratorCount; } function isAdministrator(address addr) public view returns(bool) { return _administrators[addr]; } function getCommonInitBlockNum() public view returns (uint256) { return _core.getInitBlockNum(); } function resetTokenOwnerReward() onlyController public { _tokenOwnerReward = 0; } function addTokenOwnerReward(uint256 val) onlyController public { _tokenOwnerReward = SafeMath.add(_tokenOwnerReward, val); } function getCurrentBigPromoBonus() public view returns (uint256) { return _core._currentBigPromoBonus(); } function getCurrentQuickPromoBonus() public view returns (uint256) { return _core._currentQuickPromoBonus(); } function getTotalCollectedPromoBonus() public view returns (uint256) { return _core.getTotalCollectedPromoBonus(); } function setTotalSupply(uint256 val) onlyController public { _totalSupply = val; } function setRealTokenPrice(int128 val) onlyController public { _realTokenPrice = val; } function setHasMaxPurchaseLimit(bool val) onlyController public { _hasMaxPurchaseLimit = val; } function getUserTokenLocalBalance(address userAddress) public view returns(uint256) { return _core.getUserTokenLocalBalance(address(this), userAddress); } function getActualUserTokenBalance(address userAddress) public view returns(uint256) { return SafeMath.min(getUserTokenLocalBalance(userAddress), _token.balanceOf(userAddress)); } function getBonusPerShare() public view returns(uint256) { return _core.getBonusPerShare(address(this)); } function getUserRewardPayouts(address userAddress) public view returns(uint256) { return _core.getUserRewardPayouts(address(this), userAddress); } function getUserRefBalance(address userAddress) public view returns(uint256) { return _core.getUserRefBalance(address(this), userAddress); } function getUserReward(address userAddress, bool incRefBonus, bool incPromoBonus) public view returns(uint256) { return _core.getUserReward(address(this), userAddress, true, incRefBonus, incPromoBonus); } function getUserTotalPromoBonus(address userAddress) public view returns(uint256) { return _core.getUserTotalPromoBonus(address(this), userAddress); } function getUserBigPromoBonus(address userAddress) public view returns(uint256) { return _core.getUserBigPromoBonus(address(this), userAddress); } function getUserQuickPromoBonus(address userAddress) public view returns(uint256) { return _core.getUserQuickPromoBonus(address(this), userAddress); } function getRemainingTokenAmount() public view returns(uint256) { return _token.balanceOf(_controllerAddress); } function getTotalTokenSold() public view returns(uint256) { return _totalSupply - getRemainingTokenAmount(); } function getUserEthVolumeSaldo(address userAddress) public view returns(uint256) { return _core.getUserEthVolumeSaldo(address(this), userAddress); } } contract Etherama { IStdToken public _token; EtheramaData public _data; EtheramaCore public _core; bool public isActive = false; bool public isMigrationToNewControllerInProgress = false; bool public isActualContractVer = true; address public migrationContractAddress = address(0x0); bool public isMigrationApproved = false; address private _creator = address(0x0); event onTokenPurchase(address indexed userAddress, uint256 incomingEth, uint256 tokensMinted, address indexed referredBy); event onTokenSell(address indexed userAddress, uint256 tokensBurned, uint256 ethEarned); event onReinvestment(address indexed userAddress, uint256 ethReinvested, uint256 tokensMinted); event onWithdrawTokenOwnerReward(address indexed toAddress, uint256 ethWithdrawn); event onWinQuickPromo(address indexed userAddress, uint256 ethWon); event onWinBigPromo(address indexed userAddress, uint256 ethWon); // only people with tokens modifier onlyContractUsers() { require(getUserLocalTokenBalance(msg.sender) > 0); _; } // administrators can: // -> change minimal amout of tokens to get a ref link. // administrators CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens // -> suspend the contract modifier onlyAdministrator() { require(isCurrentUserAdministrator()); _; } //core administrator can only approve contract migration after its code review modifier onlyCoreAdministrator() { require(_core.isAdministrator(msg.sender)); _; } // only active state of the contract. Administator can activate it, but canncon deactive untill lock-up period is expired. modifier onlyActive() { require(isActive); _; } // maximum gas price for buy/sell transactions to avoid "front runner" vulnerability. modifier validGasPrice() { require(tx.gasprice <= _core.MAX_GAS_PRICE()); _; } // eth value must be greater than 0 for purchase transactions modifier validPayableValue() { require(msg.value > 0); _; } modifier onlyCoreContract() { require(msg.sender == _data.getCoreAddress()); _; } // dataContractAddress - data contract address where all the data is collected and separated from the controller constructor(address dataContractAddress) public { require(dataContractAddress != address(0x0)); _data = EtheramaData(dataContractAddress); if (!_data.isInited()) { _data.init(); _data.addAdministator(msg.sender); _creator = msg.sender; } _token = _data._token(); _core = _data._core(); } function addAdministator(address addr) onlyAdministrator public { _data.addAdministator(addr); } function removeAdministator(address addr) onlyAdministrator public { _data.removeAdministator(addr); } // transfer ownership request of the contract to token owner from contract creator. The new administator has to accept ownership to finish the transferring. function transferOwnershipRequest(address addr) onlyAdministrator public { addAdministator(addr); } // accept transfer ownership. function acceptOwnership() onlyAdministrator public { require(_creator != address(0x0)); removeAdministator(_creator); require(_data.getAdministratorCount() == 1); } // if there is a maximim purchase limit then a user can buy only amount of tokens which he had before, not more. function setHasMaxPurchaseLimit(bool val) onlyAdministrator public { _data.setHasMaxPurchaseLimit(val); } // activate the controller contract. After calling this function anybody can start trading the contrant's tokens function activate() onlyAdministrator public { require(!isActive); if (getTotalTokenSupply() == 0) setTotalSupply(); require(getTotalTokenSupply() > 0); isActive = true; isMigrationToNewControllerInProgress = false; } // Close the contract and withdraw all the funds. The contract cannot be closed before lock up period is expired. function finish() onlyActive onlyAdministrator public { require(uint64(now) >= _data._expirationTime()); _token.transfer(msg.sender, getRemainingTokenAmount()); msg.sender.transfer(getTotalEthBalance()); isActive = false; } //Converts incoming eth to tokens function buy(address refAddress, uint256 minReturn) onlyActive validGasPrice validPayableValue public payable returns(uint256) { return purchaseTokens(msg.value, refAddress, minReturn); } //sell tokens for eth. before call this func you have to call "approve" in the ERC20 token contract function sell(uint256 tokenAmount, uint256 minReturn) onlyActive onlyContractUsers validGasPrice public returns(uint256) { if (tokenAmount > getCurrentUserLocalTokenBalance() || tokenAmount == 0) return 0; uint256 ethAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (ethAmount, totalFeeEth, tokenPrice) = estimateSellOrder(tokenAmount, true); require(ethAmount >= minReturn); subUserTokens(msg.sender, tokenAmount); msg.sender.transfer(ethAmount); updateTokenPrice(-_core.convert256ToReal(tokenAmount)); distributeFee(totalFeeEth, address(0x0)); uint256 userEthVol = _data.getUserEthVolumeSaldo(msg.sender); _core.trackSell(msg.sender, ethAmount > userEthVol ? userEthVol : ethAmount, tokenAmount); emit onTokenSell(msg.sender, tokenAmount, ethAmount); return ethAmount; } function transferTokens(address toUser, uint256 tokenAmount) onlyActive onlyContractUsers public { require(getUserLocalTokenBalance(msg.sender) >= tokenAmount); _core.subUserTokenLocalBalance(msg.sender, tokenAmount); _core.addUserTokenLocalBalance(toUser, tokenAmount); _token.transferFrom(msg.sender, toUser, tokenAmount); } //Fallback function to handle eth that was sent straight to the contract function() onlyActive validGasPrice validPayableValue payable external { purchaseTokens(msg.value, address(0x0), 1); } // withdraw token owner's reward function withdrawTokenOwnerReward() onlyAdministrator public { uint256 reward = getTokenOwnerReward(); require(reward > 0); _data.resetTokenOwnerReward(); msg.sender.transfer(reward); emit onWithdrawTokenOwnerReward(msg.sender, reward); } // prepare the contract for migration to another one in case of some errors or refining function prepareForMigration() onlyAdministrator public { require(!isMigrationToNewControllerInProgress); isMigrationToNewControllerInProgress = true; } // accept funds transfer to a new controller during a migration. function migrateFunds() payable public { require(isMigrationToNewControllerInProgress); } //HELPERS // max gas price for buy/sell transactions function getMaxGasPrice() public view returns(uint256) { return _core.MAX_GAS_PRICE(); } // max gas price for buy/sell transactions function getExpirationTime() public view returns (uint256) { return _data._expirationTime(); } // time till lock-up period is expired function getRemainingTimeTillExpiration() public view returns (uint256) { if (_data._expirationTime() <= uint64(now)) return 0; return _data._expirationTime() - uint64(now); } function isCurrentUserAdministrator() public view returns(bool) { return _data.isAdministrator(msg.sender); } //data contract address where all the data is holded function getDataContractAddress() public view returns(address) { return address(_data); } // get trading token contract address function getTokenAddress() public view returns(address) { return address(_token); } // request migration to new contract. After request Etherama dev team should review its code and approve it if it is OK function requestControllerContractMigration(address newControllerAddr) onlyAdministrator public { require(!isMigrationApproved); migrationContractAddress = newControllerAddr; } // Dev team gives a pervission to updagrade the contract after code review, transfer all the funds, activate new abilities or fix some errors. function approveControllerContractMigration() onlyCoreAdministrator public { isMigrationApproved = true; } //migrate to new controller contract in case of some mistake in the contract and transfer there all the tokens and eth. It can be done only after code review by Etherama developers. function migrateToNewNewControllerContract() onlyAdministrator public { require(isMigrationApproved && migrationContractAddress != address(0x0) && isActualContractVer); isActive = false; Etherama newController = Etherama(address(migrationContractAddress)); _data.setNewControllerAddress(migrationContractAddress); uint256 remainingTokenAmount = getRemainingTokenAmount(); uint256 ethBalance = getTotalEthBalance(); if (remainingTokenAmount > 0) _token.transfer(migrationContractAddress, remainingTokenAmount); if (ethBalance > 0) newController.migrateFunds.value(ethBalance)(); isActualContractVer = false; } //total buy count function getBuyCount() public view returns(uint256) { return _core.getBuyCount(getDataContractAddress()); } //total sell count function getSellCount() public view returns(uint256) { return _core.getSellCount(getDataContractAddress()); } //total eth volume function getTotalVolumeEth() public view returns(uint256) { return _core.getTotalVolumeEth(getDataContractAddress()); } //total token volume function getTotalVolumeToken() public view returns(uint256) { return _core.getTotalVolumeToken(getDataContractAddress()); } //current bonus per 1 token in ETH function getBonusPerShare() public view returns (uint256) { return SafeMath.div(SafeMath.mul(_data.getBonusPerShare(), 1 ether), _core.MAGNITUDE()); } //token initial price in ETH function getTokenInitialPrice() public view returns(uint256) { return _data.TOKEN_PRICE_INITIAL(); } function getDevRewardPercent() public view returns(uint256) { return _core._devRewardPercent(); } function getTokenOwnerRewardPercent() public view returns(uint256) { return _core._tokenOwnerRewardPercent(); } function getShareRewardPercent() public view returns(uint256) { return _core._shareRewardPercent(); } function getRefBonusPercent() public view returns(uint256) { return _core._refBonusPercent(); } function getBigPromoPercent() public view returns(uint256) { return _core._bigPromoPercent(); } function getQuickPromoPercent() public view returns(uint256) { return _core._quickPromoPercent(); } function getBigPromoBlockInterval() public view returns(uint256) { return _core._bigPromoBlockInterval(); } function getQuickPromoBlockInterval() public view returns(uint256) { return _core._quickPromoBlockInterval(); } function getPromoMinPurchaseEth() public view returns(uint256) { return _core._promoMinPurchaseEth(); } function getPriceSpeedPercent() public view returns(uint64) { return _data.PRICE_SPEED_PERCENT(); } function getPriceSpeedTokenBlock() public view returns(uint64) { return _data.PRICE_SPEED_INTERVAL(); } function getMinRefEthPurchase() public view returns (uint256) { return _core._minRefEthPurchase(); } function getTotalCollectedPromoBonus() public view returns (uint256) { return _data.getTotalCollectedPromoBonus(); } function getCurrentBigPromoBonus() public view returns (uint256) { return _data.getCurrentBigPromoBonus(); } function getCurrentQuickPromoBonus() public view returns (uint256) { return _data.getCurrentQuickPromoBonus(); } //current token price function getCurrentTokenPrice() public view returns(uint256) { return _core.convertRealTo256(_data._realTokenPrice()); } //contract's eth balance function getTotalEthBalance() public view returns(uint256) { return address(this).balance; } //amount of tokens which were funded to the contract initially function getTotalTokenSupply() public view returns(uint256) { return _data._totalSupply(); } //amount of tokens which are still available for selling on the contract function getRemainingTokenAmount() public view returns(uint256) { return _token.balanceOf(address(this)); } //amount of tokens which where sold by the contract function getTotalTokenSold() public view returns(uint256) { return getTotalTokenSupply() - getRemainingTokenAmount(); } //user's token amount which were bought from the contract function getUserLocalTokenBalance(address userAddress) public view returns(uint256) { return _data.getUserTokenLocalBalance(userAddress); } //current user's token amount which were bought from the contract function getCurrentUserLocalTokenBalance() public view returns(uint256) { return getUserLocalTokenBalance(msg.sender); } //is referal link available for the current user function isCurrentUserRefAvailable() public view returns(bool) { return _core.isRefAvailable(); } function getCurrentUserRefBonus() public view returns(uint256) { return _data.getUserRefBalance(msg.sender); } function getCurrentUserPromoBonus() public view returns(uint256) { return _data.getUserTotalPromoBonus(msg.sender); } //max and min values of a deal in tokens function getTokenDealRange() public view returns(uint256, uint256) { return (_core.MIN_TOKEN_DEAL_VAL(), _core.MAX_TOKEN_DEAL_VAL()); } //max and min values of a deal in ETH function getEthDealRange() public view returns(uint256, uint256) { uint256 minTokenVal; uint256 maxTokenVal; (minTokenVal, maxTokenVal) = getTokenDealRange(); return ( SafeMath.max(_core.MIN_ETH_DEAL_VAL(), tokensToEth(minTokenVal, true)), SafeMath.min(_core.MAX_ETH_DEAL_VAL(), tokensToEth(maxTokenVal, true)) ); } //user's total reward from all the tokens on the table. includes share reward + referal bonus + promo bonus function getUserReward(address userAddress, bool isTotal) public view returns(uint256) { return isTotal ? _core.getUserTotalReward(userAddress, true, true, true) : _data.getUserReward(userAddress, true, true); } //price for selling 1 token. mostly useful only for frontend function get1TokenSellPrice() public view returns(uint256) { uint256 tokenAmount = 1 ether; uint256 ethAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (ethAmount, totalFeeEth, tokenPrice) = estimateSellOrder(tokenAmount, true); return ethAmount; } //price for buying 1 token. mostly useful only for frontend function get1TokenBuyPrice() public view returns(uint256) { uint256 ethAmount = 1 ether; uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true); return SafeMath.div(ethAmount * 1 ether, tokenAmount); } //calc current reward for holding @tokenAmount tokens function calcReward(uint256 tokenAmount) public view returns(uint256) { return (uint256) ((int256)(_data.getBonusPerShare() * tokenAmount)) / _core.MAGNITUDE(); } //esimate buy order by amount of ETH/tokens. returns tokens/eth amount after the deal, total fee in ETH and average token price function estimateBuyOrder(uint256 amount, bool fromEth) public view returns(uint256, uint256, uint256) { uint256 minAmount; uint256 maxAmount; (minAmount, maxAmount) = fromEth ? getEthDealRange() : getTokenDealRange(); //require(amount >= minAmount && amount <= maxAmount); uint256 ethAmount = fromEth ? amount : tokensToEth(amount, true); require(ethAmount > 0); uint256 tokenAmount = fromEth ? ethToTokens(amount, true) : amount; uint256 totalFeeEth = calcTotalFee(tokenAmount, true); require(ethAmount > totalFeeEth); uint256 tokenPrice = SafeMath.div(ethAmount * 1 ether, tokenAmount); return (fromEth ? tokenAmount : SafeMath.add(ethAmount, totalFeeEth), totalFeeEth, tokenPrice); } //esimate sell order by amount of tokens/ETH. returns eth/tokens amount after the deal, total fee in ETH and average token price function estimateSellOrder(uint256 amount, bool fromToken) public view returns(uint256, uint256, uint256) { uint256 minAmount; uint256 maxAmount; (minAmount, maxAmount) = fromToken ? getTokenDealRange() : getEthDealRange(); //require(amount >= minAmount && amount <= maxAmount); uint256 tokenAmount = fromToken ? amount : ethToTokens(amount, false); require(tokenAmount > 0); uint256 ethAmount = fromToken ? tokensToEth(tokenAmount, false) : amount; uint256 totalFeeEth = calcTotalFee(tokenAmount, false); require(ethAmount > totalFeeEth); uint256 tokenPrice = SafeMath.div(ethAmount * 1 ether, tokenAmount); return (fromToken ? ethAmount : tokenAmount, totalFeeEth, tokenPrice); } //returns max user's purchase limit in tokens if _hasMaxPurchaseLimit pamam is set true. If it is a user cannot by more tokens that hs already bought on some other exchange function getUserMaxPurchase(address userAddress) public view returns(uint256) { return _token.balanceOf(userAddress) - SafeMath.mul(getUserLocalTokenBalance(userAddress), 2); } //current urser's max purchase limit in tokens function getCurrentUserMaxPurchase() public view returns(uint256) { return getUserMaxPurchase(msg.sender); } //token owener collected reward function getTokenOwnerReward() public view returns(uint256) { return _data._tokenOwnerReward(); } //current user's won promo bonuses function getCurrentUserTotalPromoBonus() public view returns(uint256) { return _data.getUserTotalPromoBonus(msg.sender); } //current user's won big promo bonuses function getCurrentUserBigPromoBonus() public view returns(uint256) { return _data.getUserBigPromoBonus(msg.sender); } //current user's won quick promo bonuses function getCurrentUserQuickPromoBonus() public view returns(uint256) { return _data.getUserQuickPromoBonus(msg.sender); } //amount of block since core contract is deployed function getBlockNumSinceInit() public view returns(uint256) { return _core.getBlockNumSinceInit(); } //remaing amount of blocks to win a quick promo bonus function getQuickPromoRemainingBlocks() public view returns(uint256) { return _core.getQuickPromoRemainingBlocks(); } //remaing amount of blocks to win a big promo bonus function getBigPromoRemainingBlocks() public view returns(uint256) { return _core.getBigPromoRemainingBlocks(); } // INTERNAL FUNCTIONS function purchaseTokens(uint256 ethAmount, address refAddress, uint256 minReturn) internal returns(uint256) { uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true); require(tokenAmount >= minReturn); if (_data._hasMaxPurchaseLimit()) { //user has to have at least equal amount of tokens which he's willing to buy require(getCurrentUserMaxPurchase() >= tokenAmount); } require(tokenAmount > 0 && (SafeMath.add(tokenAmount, getTotalTokenSold()) > getTotalTokenSold())); if (refAddress == msg.sender || !_core.isRefAvailable(refAddress)) refAddress = address(0x0); distributeFee(totalFeeEth, refAddress); addUserTokens(msg.sender, tokenAmount); // the user is not going to receive any reward for the current purchase _core.addUserRewardPayouts(msg.sender, _data.getBonusPerShare() * tokenAmount); checkAndSendPromoBonus(ethAmount); updateTokenPrice(_core.convert256ToReal(tokenAmount)); _core.trackBuy(msg.sender, ethAmount, tokenAmount); emit onTokenPurchase(msg.sender, ethAmount, tokenAmount, refAddress); return tokenAmount; } function setTotalSupply() internal { require(_data._totalSupply() == 0); uint256 tokenAmount = _token.balanceOf(address(this)); _data.setTotalSupply(tokenAmount); } function checkAndSendPromoBonus(uint256 purchaseAmountEth) internal { if (purchaseAmountEth < _data.getPromoMinPurchaseEth()) return; if (getQuickPromoRemainingBlocks() == 0) sendQuickPromoBonus(); if (getBigPromoRemainingBlocks() == 0) sendBigPromoBonus(); } function sendQuickPromoBonus() internal { _core.payoutQuickBonus(msg.sender); emit onWinQuickPromo(msg.sender, _data.getCurrentQuickPromoBonus()); } function sendBigPromoBonus() internal { _core.payoutBigBonus(msg.sender); emit onWinBigPromo(msg.sender, _data.getCurrentBigPromoBonus()); } function distributeFee(uint256 totalFeeEth, address refAddress) internal { addProfitPerShare(totalFeeEth, refAddress); addDevReward(totalFeeEth); addTokenOwnerReward(totalFeeEth); addBigPromoBonus(totalFeeEth); addQuickPromoBonus(totalFeeEth); } function addProfitPerShare(uint256 totalFeeEth, address refAddress) internal { uint256 refBonus = calcRefBonus(totalFeeEth); uint256 totalShareReward = calcTotalShareRewardFee(totalFeeEth); if (refAddress != address(0x0)) { _core.addUserRefBalance.value(refBonus)(refAddress); } else { totalShareReward = SafeMath.add(totalShareReward, refBonus); } if (getTotalTokenSold() == 0) { _data.addTokenOwnerReward(totalShareReward); } else { _core.addBonusPerShare.value(totalShareReward)(); } } function addDevReward(uint256 totalFeeEth) internal { _core.addDevReward.value(calcDevReward(totalFeeEth))(); } function addTokenOwnerReward(uint256 totalFeeEth) internal { _data.addTokenOwnerReward(calcTokenOwnerReward(totalFeeEth)); } function addBigPromoBonus(uint256 totalFeeEth) internal { _core.addBigPromoBonus.value(calcBigPromoBonus(totalFeeEth))(); } function addQuickPromoBonus(uint256 totalFeeEth) internal { _core.addQuickPromoBonus.value(calcQuickPromoBonus(totalFeeEth))(); } function addUserTokens(address user, uint256 tokenAmount) internal { _core.addUserTokenLocalBalance(user, tokenAmount); _token.transfer(msg.sender, tokenAmount); } function subUserTokens(address user, uint256 tokenAmount) internal { _core.subUserTokenLocalBalance(user, tokenAmount); _token.transferFrom(user, address(this), tokenAmount); } function updateTokenPrice(int128 realTokenAmount) public { _data.setRealTokenPrice(calc1RealTokenRateFromRealTokens(realTokenAmount)); } function ethToTokens(uint256 ethAmount, bool isBuy) internal view returns(uint256) { int128 realEthAmount = _core.convert256ToReal(ethAmount); int128 t0 = RealMath.div(realEthAmount, _data._realTokenPrice()); int128 s = getRealPriceSpeed(); int128 tn = RealMath.div(t0, RealMath.toReal(100)); for (uint i = 0; i < 100; i++) { int128 tns = RealMath.mul(tn, s); int128 exptns = RealMath.exp( RealMath.mul(tns, RealMath.toReal(isBuy ? int64(1) : int64(-1))) ); int128 tn1 = RealMath.div( RealMath.mul( RealMath.mul(tns, tn), exptns ) + t0, RealMath.mul( exptns, RealMath.toReal(1) + tns ) ); if (RealMath.abs(tn-tn1) < RealMath.fraction(1, 1e18)) break; tn = tn1; } return _core.convertRealTo256(tn); } function tokensToEth(uint256 tokenAmount, bool isBuy) internal view returns(uint256) { int128 realTokenAmount = _core.convert256ToReal(tokenAmount); int128 s = getRealPriceSpeed(); int128 expArg = RealMath.mul(RealMath.mul(realTokenAmount, s), RealMath.toReal(isBuy ? int64(1) : int64(-1))); int128 realEthAmountFor1Token = RealMath.mul(_data._realTokenPrice(), RealMath.exp(expArg)); int128 realEthAmount = RealMath.mul(realTokenAmount, realEthAmountFor1Token); return _core.convertRealTo256(realEthAmount); } function calcTotalFee(uint256 tokenAmount, bool isBuy) internal view returns(uint256) { int128 realTokenAmount = _core.convert256ToReal(tokenAmount); int128 factor = RealMath.toReal(isBuy ? int64(1) : int64(-1)); int128 rateAfterDeal = calc1RealTokenRateFromRealTokens(RealMath.mul(realTokenAmount, factor)); int128 delta = RealMath.div(rateAfterDeal - _data._realTokenPrice(), RealMath.toReal(2)); int128 fee = RealMath.mul(realTokenAmount, delta); //commission for sells is a bit lower due to rounding error if (!isBuy) fee = RealMath.mul(fee, RealMath.fraction(95, 100)); return _core.calcPercent(_core.convertRealTo256(RealMath.mul(fee, factor)), _core._totalIncomeFeePercent()); } function calc1RealTokenRateFromRealTokens(int128 realTokenAmount) internal view returns(int128) { int128 expArg = RealMath.mul(realTokenAmount, getRealPriceSpeed()); return RealMath.mul(_data._realTokenPrice(), RealMath.exp(expArg)); } function getRealPriceSpeed() internal view returns(int128) { require(RealMath.isUInt64ValidIn64(_data.PRICE_SPEED_PERCENT())); require(RealMath.isUInt64ValidIn64(_data.PRICE_SPEED_INTERVAL())); return RealMath.div(RealMath.fraction(int64(_data.PRICE_SPEED_PERCENT()), 100), RealMath.toReal(int64(_data.PRICE_SPEED_INTERVAL()))); } function calcTotalShareRewardFee(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._shareRewardPercent()); } function calcRefBonus(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._refBonusPercent()); } function calcTokenOwnerReward(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._tokenOwnerRewardPercent()); } function calcDevReward(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._devRewardPercent()); } function calcQuickPromoBonus(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._quickPromoPercent()); } function calcBigPromoBonus(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._bigPromoPercent()); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } 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 ? b : a; } } //taken from https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol and a bit modified library RealMath { int64 constant MIN_INT64 = int64((uint64(1) << 63)); int64 constant MAX_INT64 = int64(~((uint64(1) << 63))); /** * How many total bits are there? */ int256 constant REAL_BITS = 128; /** * How many fractional bits are there? */ int256 constant REAL_FBITS = 64; /** * How many integer bits are there? */ int256 constant REAL_IBITS = REAL_BITS - REAL_FBITS; /** * What's the first non-fractional bit */ int128 constant REAL_ONE = int128(1) << REAL_FBITS; /** * What's the last fractional bit? */ int128 constant REAL_HALF = REAL_ONE >> 1; /** * What's two? Two is pretty useful. */ int128 constant REAL_TWO = REAL_ONE << 1; /** * And our logarithms are based on ln(2). */ int128 constant REAL_LN_TWO = 762123384786; /** * It is also useful to have Pi around. */ int128 constant REAL_PI = 3454217652358; /** * And half Pi, to save on divides. * TODO: That might not be how the compiler handles constants. */ int128 constant REAL_HALF_PI = 1727108826179; /** * And two pi, which happens to be odd in its most accurate representation. */ int128 constant REAL_TWO_PI = 6908435304715; /** * What's the sign bit? */ int128 constant SIGN_MASK = int128(1) << 127; function getMinInt64() internal pure returns (int64) { return MIN_INT64; } function getMaxInt64() internal pure returns (int64) { return MAX_INT64; } function isUInt256ValidIn64(uint256 val) internal pure returns (bool) { return val >= 0 && val <= uint256(getMaxInt64()); } function isInt256ValidIn64(int256 val) internal pure returns (bool) { return val >= int256(getMinInt64()) && val <= int256(getMaxInt64()); } function isUInt64ValidIn64(uint64 val) internal pure returns (bool) { return val >= 0 && val <= uint64(getMaxInt64()); } function isInt128ValidIn64(int128 val) internal pure returns (bool) { return val >= int128(getMinInt64()) && val <= int128(getMaxInt64()); } /** * Convert an integer to a real. Preserves sign. */ function toReal(int64 ipart) internal pure returns (int128) { return int128(ipart) * REAL_ONE; } /** * Convert a real to an integer. Preserves sign. */ function fromReal(int128 real_value) internal pure returns (int64) { int128 intVal = real_value / REAL_ONE; require(isInt128ValidIn64(intVal)); return int64(intVal); } /** * Get the absolute value of a real. Just the same as abs on a normal int128. */ function abs(int128 real_value) internal pure returns (int128) { if (real_value > 0) { return real_value; } else { return -real_value; } } /** * Get the fractional part of a real, as a real. Ignores sign (so fpart(-0.5) is 0.5). */ function fpart(int128 real_value) internal pure returns (int128) { // This gets the fractional part but strips the sign return abs(real_value) % REAL_ONE; } /** * Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5). */ function fpartSigned(int128 real_value) internal pure returns (int128) { // This gets the fractional part but strips the sign int128 fractional = fpart(real_value); return real_value < 0 ? -fractional : fractional; } /** * Get the integer part of a fixed point value. */ function ipart(int128 real_value) internal pure returns (int128) { // Subtract out the fractional part to get the real part. return real_value - fpartSigned(real_value); } /** * Multiply one real by another. Truncates overflows. */ function mul(int128 real_a, int128 real_b) internal pure returns (int128) { // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. return int128((int256(real_a) * int256(real_b)) >> REAL_FBITS); } /** * Divide one real by another real. Truncates overflows. */ function div(int128 real_numerator, int128 real_denominator) internal pure returns (int128) { // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return int128((int256(real_numerator) * REAL_ONE) / int256(real_denominator)); } /** * Create a real from a rational fraction. */ function fraction(int64 numerator, int64 denominator) internal pure returns (int128) { return div(toReal(numerator), toReal(denominator)); } // Now we have some fancy math things (like pow and trig stuff). This isn't // in the RealMath that was deployed with the original Macroverse // deployment, so it needs to be linked into your contract statically. /** * Raise a number to a positive integer power in O(log power) time. * See <https://stackoverflow.com/a/101613> */ function ipow(int128 real_base, int64 exponent) internal pure returns (int128) { if (exponent < 0) { // Negative powers are not allowed here. revert(); } // Start with the 0th power int128 real_result = REAL_ONE; while (exponent != 0) { // While there are still bits set if ((exponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base real_result = mul(real_result, real_base); } // Shift off the low bit exponent = exponent >> 1; // Do the squaring real_base = mul(real_base, real_base); } // Return the final result. return real_result; } /** * Zero all but the highest set bit of a number. * See <https://stackoverflow.com/a/53184> */ function hibit(uint256 val) internal pure returns (uint256) { // Set all the bits below the highest set bit val |= (val >> 1); val |= (val >> 2); val |= (val >> 4); val |= (val >> 8); val |= (val >> 16); val |= (val >> 32); val |= (val >> 64); val |= (val >> 128); return val ^ (val >> 1); } /** * Given a number with one bit set, finds the index of that bit. */ function findbit(uint256 val) internal pure returns (uint8 index) { index = 0; // We and the value with alternating bit patters of various pitches to find it. if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) { // Picth 1 index |= 1; } if (val & 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC != 0) { // Pitch 2 index |= 2; } if (val & 0xF0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0 != 0) { // Pitch 4 index |= 4; } if (val & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00 != 0) { // Pitch 8 index |= 8; } if (val & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000 != 0) { // Pitch 16 index |= 16; } if (val & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000 != 0) { // Pitch 32 index |= 32; } if (val & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000 != 0) { // Pitch 64 index |= 64; } if (val & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 != 0) { // Pitch 128 index |= 128; } } /** * Shift real_arg left or right until it is between 1 and 2. Return the * rescaled value, and the number of bits of right shift applied. Shift may be negative. * * Expresses real_arg as real_scaled * 2^shift, setting shift to put real_arg between [1 and 2). * * Rejects 0 or negative arguments. */ function rescale(int128 real_arg) internal pure returns (int128 real_scaled, int64 shift) { if (real_arg <= 0) { // Not in domain! revert(); } require(isInt256ValidIn64(REAL_FBITS)); // Find the high bit int64 high_bit = findbit(hibit(uint256(real_arg))); // We'll shift so the high bit is the lowest non-fractional bit. shift = high_bit - int64(REAL_FBITS); if (shift < 0) { // Shift left real_scaled = real_arg << -shift; } else if (shift >= 0) { // Shift right real_scaled = real_arg >> shift; } } /** * Calculate the natural log of a number. Rescales the input value and uses * the algorithm outlined at <https://math.stackexchange.com/a/977836> and * the ipow implementation. * * Lets you artificially limit the number of iterations. * * Note that it is potentially possible to get an un-converged value; lack * of convergence does not throw. */ function lnLimited(int128 real_arg, int max_iterations) internal pure returns (int128) { if (real_arg <= 0) { // Outside of acceptable domain revert(); } if (real_arg == REAL_ONE) { // Handle this case specially because people will want exactly 0 and // not ~2^-39 ish. return 0; } // We know it's positive, so rescale it to be between [1 and 2) int128 real_rescaled; int64 shift; (real_rescaled, shift) = rescale(real_arg); // Compute the argument to iterate on int128 real_series_arg = div(real_rescaled - REAL_ONE, real_rescaled + REAL_ONE); // We will accumulate the result here int128 real_series_result = 0; for (int64 n = 0; n < max_iterations; n++) { // Compute term n of the series int128 real_term = div(ipow(real_series_arg, 2 * n + 1), toReal(2 * n + 1)); // And add it in real_series_result += real_term; if (real_term == 0) { // We must have converged. Next term is too small to represent. break; } // If we somehow never converge I guess we will run out of gas } // Double it to account for the factor of 2 outside the sum real_series_result = mul(real_series_result, REAL_TWO); // Now compute and return the overall result return mul(toReal(shift), REAL_LN_TWO) + real_series_result; } /** * Calculate a natural logarithm with a sensible maximum iteration count to * wait until convergence. Note that it is potentially possible to get an * un-converged value; lack of convergence does not throw. */ function ln(int128 real_arg) internal pure returns (int128) { return lnLimited(real_arg, 100); } /** * Calculate e^x. Uses the series given at * <http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html>. * * Lets you artificially limit the number of iterations. * * Note that it is potentially possible to get an un-converged value; lack * of convergence does not throw. */ function expLimited(int128 real_arg, int max_iterations) internal pure returns (int128) { // We will accumulate the result here int128 real_result = 0; // We use this to save work computing terms int128 real_term = REAL_ONE; for (int64 n = 0; n < max_iterations; n++) { // Add in the term real_result += real_term; // Compute the next term real_term = mul(real_term, div(real_arg, toReal(n + 1))); if (real_term == 0) { // We must have converged. Next term is too small to represent. break; } // If we somehow never converge I guess we will run out of gas } // Return the result return real_result; } function expLimited(int128 real_arg, int max_iterations, int k) internal pure returns (int128) { // We will accumulate the result here int128 real_result = 0; // We use this to save work computing terms int128 real_term = REAL_ONE; for (int64 n = 0; n < max_iterations; n++) { // Add in the term real_result += real_term; // Compute the next term real_term = mul(real_term, div(real_arg, toReal(n + 1))); if (real_term == 0) { // We must have converged. Next term is too small to represent. break; } if (n == k) return real_term; // If we somehow never converge I guess we will run out of gas } // Return the result return real_result; } /** * Calculate e^x with a sensible maximum iteration count to wait until * convergence. Note that it is potentially possible to get an un-converged * value; lack of convergence does not throw. */ function exp(int128 real_arg) internal pure returns (int128) { return expLimited(real_arg, 100); } /** * Raise any number to any power, except for negative bases to fractional powers. */ function pow(int128 real_base, int128 real_exponent) internal pure returns (int128) { if (real_exponent == 0) { // Anything to the 0 is 1 return REAL_ONE; } if (real_base == 0) { if (real_exponent < 0) { // Outside of domain! revert(); } // Otherwise it's 0 return 0; } if (fpart(real_exponent) == 0) { // Anything (even a negative base) is super easy to do to an integer power. if (real_exponent > 0) { // Positive integer power is easy return ipow(real_base, fromReal(real_exponent)); } else { // Negative integer power is harder return div(REAL_ONE, ipow(real_base, fromReal(-real_exponent))); } } if (real_base < 0) { // It's a negative base to a non-integer power. // In general pow(-x^y) is undefined, unless y is an int or some // weird rational-number-based relationship holds. revert(); } // If it's not a special case, actually do it. return exp(mul(real_exponent, ln(real_base))); } }
current user's reward
function getCurrentUserReward(bool incRefBonus, bool incPromoBonus) public view returns(uint256) { return getUserTotalReward(msg.sender, true, incRefBonus, incPromoBonus); }
1,321,816
pragma solidity ^0.4.23; pragma experimental ABIEncoderV2; contract GuessNumber { enum ActionType { GUESS, CLUE, REVEAL } struct Action{ uint8 guess; bool clue; string secret; ActionType actionType; address sender; } address public disputer; uint256 timeoutInterval; struct GameState { address whoseTurn; address guesser; address dealer; bool[5] clues; uint8[5] guesses; bytes32 secretHash; bool gameStarted; uint stake; uint seq; address winner; address contractAddress; } GameState public onChainState; event AcceptGame(GameState gameState); event StartDispute(GameState gameState, address starter); event EndDispute(GameState gameState); event UpdateTimeout(uint256 newTimeout, address whoseTurn); constructor(bytes32 _secretHash) public payable { require(msg.value > 0); uint8[5] tempGuesses; bool[5] tempClues; onChainState = GameState({ whoseTurn: msg.sender, guesser: address(0), dealer: msg.sender, clues:tempClues, guesses: tempGuesses, secretHash: _secretHash, gameStarted: false, stake: msg.value, seq: 0, winner: address(0), contractAddress: address(this) }); timeoutInterval = 3600; timeout = 2**256 - 1; } // during a dispate: making a move directly ends it happily // jumping to a DIFFERNT later or = state leads to slashing // starting a dispute means jumping to state (and possibly aslo moving), or just moving function applyActionToChainState(Action action) public payout updateTimeout { // ensure sender is the real sender:(require it instead of overwriting? whatever) action.sender = msg.sender; onChainState = applyAction(onChainState, action); if (disputer == opponentOf (onChainState, msg.sender)){ endDispute(); } else if (disputer == address(0)){ startDispute(); } } // TODO is this safe, i.e, private should be impossible to call directly? function startDispute() private { disputer = msg.sender; emit StartDispute(getOnChainState(), msg.sender); } function endDispute() private { disputer = address(0); emit EndDispute(onChainState); } function getOnChainState() public view returns(GameState){ return onChainState; } function stateToFullDigest(GameState gameState) public pure returns (bytes32){ bytes32 inputAppHash = stateToHash(gameState); // TODO: purify address this return prefixed(keccak256(gameState.contractAddress, inputAppHash)); } // Might not need this? function stateToHash(GameState gameState) public pure returns (bytes32){ return keccak256(abi.encode(gameState)); } function jumpToStateOnChain(GameState gameState, bytes sig, Action action) public payout updateTimeout returns (bool){ bytes32 inputStateHash = stateToFullDigest(gameState); require(recoverSigner(inputStateHash, sig) == opponentOf(gameState, msg.sender)); // happy case: players agreed on winner, stop here if (gameState.winner != address(0) ){ return true; } require(gameState.seq >= onChainState.seq); // for dispute, but may as well always check: don't jump to redundant state (player could have honestly applied action) require(stateToFullDigest(onChainState) != stateToFullDigest(gameState)); if (disputer == address(0)){ onChainState = gameState; // if initiating a dispute at current turn, have to make a move in same transaction (if not, or if this is settling a dispute, action can be a dummy action) if (onChainState.whoseTurn == msg.sender){ applyActionToChainState(action); } startDispute(); } else if (disputer == opponentOf(gameState, msg.sender)){ onChainState.winner = msg.sender; } return true; } modifier updateTimeout (){ timeout = now + timeoutInterval; emit UpdateTimeout(timeout, onChainState.whoseTurn); _; } function claimTimeout() payout payable{ require(onChainState.winner == address(0)); require(onChainState.whoseTurn == opponentOf(onChainState, msg.sender)); require(now > timeout); onChainState.winner = msg.sender; } function test(string s) returns(bytes32){ return keccak256(s); } function testGetClues() public returns (bool[5]){ return onChainState.clues; } function stringToUint(string s) constant returns (uint result) { bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); } } } modifier payout() { _; if(onChainState.winner!= address(0)) { onChainState.winner.transfer(address(this).balance); onChainState.gameStarted = false; } } function acceptGame() public payable updateTimeout { require(msg.value >= onChainState.stake); require(!onChainState.gameStarted); onChainState.gameStarted = true; onChainState.whoseTurn = msg.sender; onChainState.guesser = msg.sender; emit AcceptGame(getOnChainState()); } function applyAction(GameState gameState, Action action)public view turnTaker(gameState, action.sender) returns(GameState){ if(action.actionType == ActionType.GUESS){ return submitGuess(gameState, action); } else if (action.actionType == ActionType.CLUE){ return submitClue(gameState, action); } else if (action.actionType == ActionType.REVEAL){ return reveal(gameState, action); } } function submitGuess( GameState gameState, Action action) pure public returns (GameState){ require(action.guess < 100); require(action.guess > 0); gameState.guesses[gameState.seq/2] = action.guess; return gameState; } function submitClue( GameState gameState, Action action) pure public returns (GameState){ // todo: divide by 2 7 round down require(gameState.seq < 10); gameState.clues[gameState.seq/2] = action.clue; return gameState; } function reveal(GameState gameState, Action action) returns (GameState){ // why do I have this? // require(msg.sender == gameState.dealer); if (keccak256(action.secret) != gameState.secretHash ){ gameState.winner = opponentOf(gameState, action.sender); } else { // getnumber uint winningNumber = stringToUint(action.secret) % 100; uint8 currentGuess; bool currentClue; for (uint i=0; i<gameState.guesses.length; i++) { currentGuess = gameState.guesses[i]; currentClue = gameState.clues[i]; if (currentGuess == winningNumber || currentGuess==0){ gameState.winner = gameState.guesser; return gameState; } if ( (currentGuess < winningNumber && currentClue) ||(currentGuess > winningNumber && !currentClue) ) { gameState.winner = gameState.guesser; return gameState; } } // TODO edgecase for if he doesn't submit last clue ? meh // if gueser didn't make all of his guesses yet, guesser wins (check for zeros? requrie this up front) // otherwise, dealer wins, } return gameState; } function opponentOf(GameState gameState, address player)public pure returns(address){ if (player == gameState.dealer){ return gameState.guesser; } else if (player== gameState.guesser){ return gameState.dealer; } require(false); } modifier turnTaker(GameState gameState, address sender) { require(gameState.winner == address(0)); require(sender == gameState.whoseTurn); require(gameState.gameStarted); gameState.seq++; gameState.whoseTurn = opponentOf(gameState, sender); _; } // Signature methods function splitSignature(bytes sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recoverSigner(bytes32 message, bytes sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } // Builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256("\x19Ethereum Signed Message:\n32", hash); } }
Builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256("\x19Ethereum Signed Message:\n32", hash); }
13,026,692
/* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { IClaimAdapter } from "../../interfaces/IClaimAdapter.sol"; import { IController } from "../../interfaces/IController.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; /** * @title ClaimModule * @author Set Protocol * * Module that enables managers to claim tokens from external protocols given to the Set as part of participating in * incentivized activities of other protocols. The ClaimModule works in conjunction with ClaimAdapters, in which the * claimAdapterID / integrationNames are stored on the integration registry. * * Design: * The ecosystem is coalescing around a few standards of how reward programs are created, using forks of popular * contracts such as Synthetix's Mintr. Thus, the Claim architecture reflects a more functional vs external-protocol * approach where an adapter with common functionality can be used across protocols. * * Definitions: * Reward Pool: A reward pool is a contract associated with an external protocol's reward. Examples of reward pools * include the Curve sUSDV2 Gauge or the Synthetix iBTC StakingReward contract. * Adapter: An adapter contains the logic and context for how a reward pool should be claimed - returning the requisite * function signature. Examples of adapters include StakingRewardAdapter (for getting rewards from Synthetix-like * reward contracts) and CurveClaimAdapter (for calling Curve Minter contract's mint function) * ClaimSettings: A reward pool can be associated with multiple awards. For example, a Curve liquidity gauge can be * associated with the CURVE_CLAIM adapter to claim CRV and CURVE_DIRECT adapter to claim BPT. */ contract ClaimModule is ModuleBase { using AddressArrayUtils for address[]; /* ============ Events ============ */ event RewardClaimed( ISetToken indexed _setToken, address indexed _rewardPool, IClaimAdapter indexed _adapter, uint256 _amount ); event AnyoneClaimUpdated( ISetToken indexed _setToken, bool _anyoneClaim ); /* ============ Modifiers ============ */ /** * Throws if claim is confined to the manager and caller is not the manager */ modifier onlyValidCaller(ISetToken _setToken) { require(_isValidCaller(_setToken), "Must be valid caller"); _; } /* ============ State Variables ============ */ // Indicates if any address can call claim or just the manager of the SetToken mapping(ISetToken => bool) public anyoneClaim; // Map and array of rewardPool addresses to claim rewards for the SetToken mapping(ISetToken => address[]) public rewardPoolList; // Map from set tokens to rewards pool address to isAdded boolean. Used to check if a reward pool has been added in O(1) time mapping(ISetToken => mapping(address => bool)) public rewardPoolStatus; // Map and array of adapters associated to the rewardPool for the SetToken mapping(ISetToken => mapping(address => address[])) public claimSettings; // Map from set tokens to rewards pool address to claim adapters to isAdded boolean. Used to check if an adapter has been added in O(1) time mapping(ISetToken => mapping(address => mapping(address => bool))) public claimSettingsStatus; /* ============ Constructor ============ */ constructor(IController _controller) public ModuleBase(_controller) {} /* ============ External Functions ============ */ /** * Claim the rewards available on the rewardPool for the specified claim integration. * Callable only by manager unless manager has set anyoneClaim to true. * * @param _setToken Address of SetToken * @param _rewardPool Address of the rewardPool that identifies the contract governing claims * @param _integrationName ID of claim module integration (mapping on integration registry) */ function claim( ISetToken _setToken, address _rewardPool, string calldata _integrationName ) external onlyValidAndInitializedSet(_setToken) onlyValidCaller(_setToken) { _claim(_setToken, _rewardPool, _integrationName); } /** * Claims rewards on all the passed rewardPool/claim integration pairs. Callable only by manager unless manager has * set anyoneClaim to true. * * @param _setToken Address of SetToken * @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same * index integrationNames * @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index * in rewardPools */ function batchClaim( ISetToken _setToken, address[] calldata _rewardPools, string[] calldata _integrationNames ) external onlyValidAndInitializedSet(_setToken) onlyValidCaller(_setToken) { uint256 poolArrayLength = _validateBatchArrays(_rewardPools, _integrationNames); for (uint256 i = 0; i < poolArrayLength; i++) { _claim(_setToken, _rewardPools[i], _integrationNames[i]); } } /** * SET MANAGER ONLY. Update whether manager allows other addresses to call claim. * * @param _setToken Address of SetToken */ function updateAnyoneClaim(ISetToken _setToken, bool _anyoneClaim) external onlyManagerAndValidSet(_setToken) { anyoneClaim[_setToken] = _anyoneClaim; emit AnyoneClaimUpdated(_setToken, _anyoneClaim); } /** * SET MANAGER ONLY. Adds a new claim integration for an existent rewardPool. If rewardPool doesn't have existing * claims then rewardPool is added to rewardPoolLiost. The claim integration is associated to an adapter that * provides the functionality to claim the rewards for a specific token. * * @param _setToken Address of SetToken * @param _rewardPool Address of the rewardPool that identifies the contract governing claims * @param _integrationName ID of claim module integration (mapping on integration registry) */ function addClaim( ISetToken _setToken, address _rewardPool, string calldata _integrationName ) external onlyManagerAndValidSet(_setToken) { _addClaim(_setToken, _rewardPool, _integrationName); } /** * SET MANAGER ONLY. Adds a new rewardPool to the list to perform claims for the SetToken indicating the list of * claim integrations. Each claim integration is associated to an adapter that provides the functionality to claim * the rewards for a specific token. * * @param _setToken Address of SetToken * @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same * index integrationNames * @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index * in rewardPools */ function batchAddClaim( ISetToken _setToken, address[] calldata _rewardPools, string[] calldata _integrationNames ) external onlyManagerAndValidSet(_setToken) { _batchAddClaim(_setToken, _rewardPools, _integrationNames); } /** * SET MANAGER ONLY. Removes a claim integration from an existent rewardPool. If no claim remains for reward pool then * reward pool is removed from rewardPoolList. * * @param _setToken Address of SetToken * @param _rewardPool Address of the rewardPool that identifies the contract governing claims * @param _integrationName ID of claim module integration (mapping on integration registry) */ function removeClaim( ISetToken _setToken, address _rewardPool, string calldata _integrationName ) external onlyManagerAndValidSet(_setToken) { _removeClaim(_setToken, _rewardPool, _integrationName); } /** * SET MANAGER ONLY. Batch removes claims from SetToken's settings. * * @param _setToken Address of SetToken * @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same index * integrationNames * @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index in * rewardPools */ function batchRemoveClaim( ISetToken _setToken, address[] calldata _rewardPools, string[] calldata _integrationNames ) external onlyManagerAndValidSet(_setToken) { uint256 poolArrayLength = _validateBatchArrays(_rewardPools, _integrationNames); for (uint256 i = 0; i < poolArrayLength; i++) { _removeClaim(_setToken, _rewardPools[i], _integrationNames[i]); } } /** * SET MANAGER ONLY. Initializes this module to the SetToken. * * @param _setToken Instance of the SetToken to issue * @param _anyoneClaim Boolean indicating if anyone can claim or just manager * @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same index * integrationNames * @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index in * rewardPools */ function initialize( ISetToken _setToken, bool _anyoneClaim, address[] calldata _rewardPools, string[] calldata _integrationNames ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { _batchAddClaim(_setToken, _rewardPools, _integrationNames); anyoneClaim[_setToken] = _anyoneClaim; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. */ function removeModule() external override { delete anyoneClaim[ISetToken(msg.sender)]; // explicitly delete all elements for gas refund address[] memory setTokenPoolList = rewardPoolList[ISetToken(msg.sender)]; for (uint256 i = 0; i < setTokenPoolList.length; i++) { address[] storage adapterList = claimSettings[ISetToken(msg.sender)][setTokenPoolList[i]]; for (uint256 j = 0; j < adapterList.length; j++) { address toRemove = adapterList[j]; claimSettingsStatus[ISetToken(msg.sender)][setTokenPoolList[i]][toRemove] = false; delete adapterList[j]; } delete claimSettings[ISetToken(msg.sender)][setTokenPoolList[i]]; } for (uint256 i = 0; i < rewardPoolList[ISetToken(msg.sender)].length; i++) { address toRemove = rewardPoolList[ISetToken(msg.sender)][i]; rewardPoolStatus[ISetToken(msg.sender)][toRemove] = false; delete rewardPoolList[ISetToken(msg.sender)][i]; } delete rewardPoolList[ISetToken(msg.sender)]; } /** * Get list of rewardPools to perform claims for the SetToken. * * @param _setToken Address of SetToken * @return Array of rewardPool addresses to claim rewards for the SetToken */ function getRewardPools(ISetToken _setToken) external view returns (address[] memory) { return rewardPoolList[_setToken]; } /** * Get boolean indicating if the rewardPool is in the list to perform claims for the SetToken. * * @param _setToken Address of SetToken * @param _rewardPool Address of rewardPool * @return Boolean indicating if the rewardPool is in the list for claims. */ function isRewardPool(ISetToken _setToken, address _rewardPool) public view returns (bool) { return rewardPoolStatus[_setToken][_rewardPool]; } /** * Get list of claim integration of the rewardPool for the SetToken. * * @param _setToken Address of SetToken * @param _rewardPool Address of rewardPool * @return Array of adapter addresses associated to the rewardPool for the SetToken */ function getRewardPoolClaims(ISetToken _setToken, address _rewardPool) external view returns (address[] memory) { return claimSettings[_setToken][_rewardPool]; } /** * Get boolean indicating if the adapter address of the claim integration is associated to the rewardPool. * * @param _setToken Address of SetToken * @param _rewardPool Address of rewardPool * @param _integrationName ID of claim module integration (mapping on integration registry) * @return Boolean indicating if the claim integration is associated to the rewardPool. */ function isRewardPoolClaim( ISetToken _setToken, address _rewardPool, string calldata _integrationName ) external view returns (bool) { address adapter = getAndValidateAdapter(_integrationName); return claimSettingsStatus[_setToken][_rewardPool][adapter]; } /** * Get the rewards available to be claimed by the claim integration on the rewardPool. * * @param _setToken Address of SetToken * @param _rewardPool Address of the rewardPool that identifies the contract governing claims * @param _integrationName ID of claim module integration (mapping on integration registry) * @return rewards Amount of units available to be claimed */ function getRewards( ISetToken _setToken, address _rewardPool, string calldata _integrationName ) external view returns (uint256) { IClaimAdapter adapter = _getAndValidateIntegrationAdapter(_setToken, _rewardPool, _integrationName); return adapter.getRewardsAmount(_setToken, _rewardPool); } /* ============ Internal Functions ============ */ /** * Claim the rewards, if available, on the rewardPool using the specified adapter. Interact with the adapter to get * the rewards available, the calldata for the SetToken to invoke the claim and the token associated to the claim. * * @param _setToken Address of SetToken * @param _rewardPool Address of the rewardPool that identifies the contract governing claims * @param _integrationName Human readable name of claim integration */ function _claim(ISetToken _setToken, address _rewardPool, string calldata _integrationName) internal { require(isRewardPool(_setToken, _rewardPool), "RewardPool not present"); IClaimAdapter adapter = _getAndValidateIntegrationAdapter(_setToken, _rewardPool, _integrationName); IERC20 rewardsToken = IERC20(adapter.getTokenAddress(_rewardPool)); uint256 initRewardsBalance = rewardsToken.balanceOf(address(_setToken)); ( address callTarget, uint256 callValue, bytes memory callByteData ) = adapter.getClaimCallData( _setToken, _rewardPool ); _setToken.invoke(callTarget, callValue, callByteData); uint256 finalRewardsBalance = rewardsToken.balanceOf(address(_setToken)); emit RewardClaimed(_setToken, _rewardPool, adapter, finalRewardsBalance.sub(initRewardsBalance)); } /** * Gets the adapter and validate it is associated to the list of claim integration of a rewardPool. * * @param _setToken Address of SetToken * @param _rewardsPool Sddress of rewards pool * @param _integrationName ID of claim module integration (mapping on integration registry) */ function _getAndValidateIntegrationAdapter( ISetToken _setToken, address _rewardsPool, string calldata _integrationName ) internal view returns (IClaimAdapter) { address adapter = getAndValidateAdapter(_integrationName); require(claimSettingsStatus[_setToken][_rewardsPool][adapter], "Adapter integration not present"); return IClaimAdapter(adapter); } /** * Validates and store the adapter address used to claim rewards for the passed rewardPool. If after adding * adapter to pool length of adapters is 1 then add to rewardPoolList as well. * * @param _setToken Address of SetToken * @param _rewardPool Address of the rewardPool that identifies the contract governing claims * @param _integrationName ID of claim module integration (mapping on integration registry) */ function _addClaim(ISetToken _setToken, address _rewardPool, string calldata _integrationName) internal { address adapter = getAndValidateAdapter(_integrationName); address[] storage _rewardPoolClaimSettings = claimSettings[_setToken][_rewardPool]; require(!claimSettingsStatus[_setToken][_rewardPool][adapter], "Integration names must be unique"); _rewardPoolClaimSettings.push(adapter); claimSettingsStatus[_setToken][_rewardPool][adapter] = true; if (!rewardPoolStatus[_setToken][_rewardPool]) { rewardPoolList[_setToken].push(_rewardPool); rewardPoolStatus[_setToken][_rewardPool] = true; } } /** * Internal version. Adds a new rewardPool to the list to perform claims for the SetToken indicating the list of claim * integrations. Each claim integration is associated to an adapter that provides the functionality to claim the rewards * for a specific token. * * @param _setToken Address of SetToken * @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same * index integrationNames * @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index * in rewardPools */ function _batchAddClaim( ISetToken _setToken, address[] calldata _rewardPools, string[] calldata _integrationNames ) internal { uint256 poolArrayLength = _validateBatchArrays(_rewardPools, _integrationNames); for (uint256 i = 0; i < poolArrayLength; i++) { _addClaim(_setToken, _rewardPools[i], _integrationNames[i]); } } /** * Validates and stores the adapter address used to claim rewards for the passed rewardPool. If no adapters * left after removal then remove rewardPool from rewardPoolList and delete entry in claimSettings. * * @param _setToken Address of SetToken * @param _rewardPool Address of the rewardPool that identifies the contract governing claims * @param _integrationName ID of claim module integration (mapping on integration registry) */ function _removeClaim(ISetToken _setToken, address _rewardPool, string calldata _integrationName) internal { address adapter = getAndValidateAdapter(_integrationName); require(claimSettingsStatus[_setToken][_rewardPool][adapter], "Integration must be added"); claimSettings[_setToken][_rewardPool].removeStorage(adapter); claimSettingsStatus[_setToken][_rewardPool][adapter] = false; if (claimSettings[_setToken][_rewardPool].length == 0) { rewardPoolList[_setToken].removeStorage(_rewardPool); rewardPoolStatus[_setToken][_rewardPool] = false; } } /** * For batch functions validate arrays are of equal length and not empty. Return length of array for iteration. * * @param _rewardPools Addresses of the rewardPool that identifies the contract governing claims * @param _integrationNames IDs of claim module integration (mapping on integration registry) * @return Length of arrays */ function _validateBatchArrays( address[] memory _rewardPools, string[] calldata _integrationNames ) internal pure returns(uint256) { uint256 poolArrayLength = _rewardPools.length; require(poolArrayLength == _integrationNames.length, "Array length mismatch"); require(poolArrayLength > 0, "Arrays must not be empty"); return poolArrayLength; } /** * If claim is confined to the manager, manager must be caller * * @param _setToken Address of SetToken * @return bool Whether or not the caller is valid */ function _isValidCaller(ISetToken _setToken) internal view returns(bool) { return anyoneClaim[_setToken] || isSetManager(_setToken, msg.sender); } }
Get boolean indicating if the adapter address of the claim integration is associated to the rewardPool. _setToken Address of SetToken _rewardPool Address of rewardPool _integrationName ID of claim module integration (mapping on integration registry) return Boolean indicating if the claim integration is associated to the rewardPool./
function isRewardPoolClaim( ISetToken _setToken, address _rewardPool, string calldata _integrationName ) external view returns (bool) { address adapter = getAndValidateAdapter(_integrationName); return claimSettingsStatus[_setToken][_rewardPool][adapter]; }
12,620,126
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./../interfaces/compound/Comptroller.sol"; import "./../interfaces/compound/CErc20.sol"; import "./../interfaces/erc20/Erc20.sol"; import "./IRouter.sol"; import "./../dex/Uniswap.sol"; import "./../math/SafeMath.sol"; import "./../math/SignedSafeMath.sol"; import "./../math/DSMath.sol"; contract CompoundRouter is IRouter, Uniswap { Comptroller private _comptroller; Erc20 private _underlyingAsset; CErc20 private _cToken; Erc20 private _compToken; /// @dev Logging and debugging event // event Log(string, uint256); constructor( address _comptrollerAddress, address _underlyingAssetAddress, address _cTokenAddress, address _uniswapRouterAddress ) public Uniswap(_uniswapRouterAddress) { _comptroller = Comptroller(_comptrollerAddress); _underlyingAsset = Erc20(_underlyingAssetAddress); _cToken = CErc20(_cTokenAddress); address compTokenAddress = _comptroller.getCompAddress(); _compToken = Erc20(compTokenAddress); _enterMarkets(); } /// @dev Enter the Compound market to provide liquidity function _enterMarkets() internal { address[] memory cTokens = new address[](1); cTokens[0] = address(_cToken); uint256[] memory errors = _comptroller.enterMarkets(cTokens); if (errors[0] != 0) { revert("Comptroller.enterMarkets Error"); } } /// @dev Supply underlying asset to protocol function _supplyUnderlying(uint256 _amount) internal { _underlyingAsset.approve(address(_cToken), _amount); uint256 mintError = _cToken.mint(_amount); require(mintError == 0, "CErc20.mint Error"); // emit Log("Supplied", _amount); } /// @dev Redeem cTokens for underlying asset function _redeemUnderlying(uint256 _amount) internal { uint256 redeemError = _cToken.redeem(_amount); require(redeemError == 0, "CErc20.redeem Error"); // emit Log("Redeemed", _amount); } /** * @dev Get the current APY * * Rate = cToken.supplyRatePerBlock(); * ETH Mantissa = 1 * 10 ^ 18 (ETH has 18 decimal places) * Blocks Per Day = 4 * 60 * 24 (based on 4 blocks occurring every minute) * Days Per Year = 365 * * APY in RAY units = ((((Rate / ETH Mantissa * Blocks Per Day + 1) ^ Days Per Year)) - 1) * APY percentage in RAY units = ((((Rate / ETH Mantissa * Blocks Per Day + 1) ^ Days Per Year)) - 1) * 100 */ function getCurrentAPY() external view override returns (uint256) { uint256 supplyRate = _cToken.supplyRatePerBlock(); uint256 mantissa = 10**18; uint256 blocksPerDay = 4 * 60 * 24; // 4 blocks per minute uint256 daysPerYear = 365; uint256 base = DSMath.mul(DSMath.rdiv(supplyRate, mantissa), blocksPerDay); base = DSMath.add(base, DSMath.RAY); uint256 power = DSMath.rpow(base, daysPerYear); uint256 apy = DSMath.sub(power, DSMath.RAY); return apy; } function getUnderlyingAsset() external view override returns (address) { return address(_underlyingAsset); } function getUnderlyingDecimals() external view override returns (uint256) { return _underlyingAsset.decimals(); } function deposit(uint256 _amount) external override { // Caller must approve contract before calling this function require( _underlyingAsset.transferFrom(msg.sender, address(this), _amount), "Transfer failed" ); _supplyUnderlying(_amount); emit Deposit(_amount); } function withdraw() external override { uint256 balancecToken = _cToken.balanceOf(address(this)); _redeemUnderlying(balancecToken); this.harvest(); uint256 balance = _underlyingAsset.balanceOf(address(this)); require( _underlyingAsset.transfer(msg.sender, balance), "Transfer failed" ); emit Withdrawal(balance); } function harvest() external override { _comptroller.claimComp(address(this)); uint256 amountIn = _compToken.balanceOf(address(this)); this.swapTokensAForTokensB( address(_compToken), address(_underlyingAsset), amountIn ); emit Harvest(amountIn); } }
Supply underlying asset to protocol emit Log("Supplied", _amount);
function _supplyUnderlying(uint256 _amount) internal { _underlyingAsset.approve(address(_cToken), _amount); uint256 mintError = _cToken.mint(_amount); require(mintError == 0, "CErc20.mint Error"); }
6,477,977
pragma solidity ^0.5.0; /// @title Ownable Contract contract Ownable { /// @notice Storage position of the owner address /// @dev The address of the current owner is stored in a /// constant pseudorandom slot of the contract storage /// (slot number obtained as a result of hashing a certain message), /// the probability of rewriting which is almost zero bytes32 private constant _ownerPosition = keccak256("owner"); /// @notice Storage position of the authorized new owner address bytes32 private constant _authorizedNewOwnerPosition = keccak256("authorizedNewOwner"); /// @notice Contract constructor /// @dev Sets msg sender address as owner address constructor() public { bytes32 ownerPosition = _ownerPosition; address owner = msg.sender; assembly { sstore(ownerPosition, owner) } } /// @notice Check that requires msg.sender to be the current owner function requireOwner() internal view { require( msg.sender == getOwner(), "Sender must be owner" ); } /// @notice Returns contract owner address function getOwner() public view returns (address owner) { bytes32 ownerPosition = _ownerPosition; assembly { owner := sload(ownerPosition) } } /// @notice Returns authorized new owner address function getAuthorizedNewOwner() public view returns (address newOwner) { bytes32 authorizedNewOwnerPosition = _authorizedNewOwnerPosition; assembly { newOwner := sload(authorizedNewOwnerPosition) } } /** * @notice Authorizes the transfer of ownership to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). * This authorization may be removed by another call to this function authorizing * the null address. * * @param authorizedAddress The address authorized to become the new owner. */ function authorizeOwnershipTransfer(address authorizedAddress) external { requireOwner(); bytes32 authorizedNewOwnerPosition = _authorizedNewOwnerPosition; assembly { sstore(authorizedNewOwnerPosition, authorizedAddress) } } /** * @notice Transfers ownership of this contract to the authorizedNewOwner. */ function assumeOwnership() external { bytes32 authorizedNewOwnerPosition = _authorizedNewOwnerPosition; address newOwner; assembly { newOwner := sload(authorizedNewOwnerPosition) } require( msg.sender == newOwner, "Only the authorized new owner can accept ownership" ); bytes32 ownerPosition = _ownerPosition; address zero = address(0); assembly { sstore(ownerPosition, newOwner) sstore(authorizedNewOwnerPosition, zero) } } }
Authorizes the transfer of ownership to the provided address. NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). This authorization may be removed by another call to this function authorizing the null address. authorizedAddress The address authorized to become the new owner./
function authorizeOwnershipTransfer(address authorizedAddress) external { requireOwner(); bytes32 authorizedNewOwnerPosition = _authorizedNewOwnerPosition; assembly { sstore(authorizedNewOwnerPosition, authorizedAddress) } }
15,830,568
./partial_match/1/0x6Ea3966187E86242965aB29Bc9dA9486B9fB8586/sources/contracts/FCNProduct.sol
Transfers assets from the user to the product amount is the amount of assets being deposited receiver is the address of the user depositing into the product/
function addToDepositQueue(uint256 amount, address receiver) public { require(isDepositQueueOpen, "500:NotOpen"); require(amount >= minDepositAmount, "400:DA"); queuedDepositsCount += 1; queuedDepositsTotalAmount += amount; require(queuedDepositsTotalAmount + sumVaultUnderlyingAmounts <= maxDepositAmountLimit, "500:TooBig"); IERC20(asset).safeTransferFrom(receiver, address(this), amount); emit DepositQueued(receiver, amount); }
3,646,546
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; bool public transfersEnabled; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 { uint256 public totalSupply; bool public transfersEnabled; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => uint256) balances; mapping (address => bool) public whitelistPayee; /** * Protection against short address attack */ modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } function checkTransfer(address _to) public view { bool permit = false; if (!transfersEnabled) { if (whitelistPayee[_to]) { permit = true; } } else { permit = true; } require(permit); } /** * @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 onlyPayloadSize(2) returns (bool) { checkTransfer(_to); require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } 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 onlyPayloadSize(3) returns (bool) { checkTransfer(_to); require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public onlyPayloadSize(2) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit 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); } emit 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; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } } /** * @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 { string public constant name = "PHOENIX INVESTMENT FUND"; string public constant symbol = "PHI"; uint8 public constant decimals = 18; event Mint(address indexed to, uint256 amount); bool public mintingFinished; 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, address _owner) canMint internal returns (bool) { require(_to != address(0)); require(_owner != address(0)); require(_amount <= balances[_owner]); balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); emit Mint(_to, _amount); emit Transfer(_owner, _to, _amount); return true; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens(address _token) public onlyOwner { if (_token == 0x0) { owner.transfer(address(this).balance); return; } MintableToken token = MintableToken(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); emit Transfer(_token, owner, balance); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale is Ownable { // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; uint256 public tokenAllocated; constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; } } contract PHICrowdsale is Ownable, Crowdsale, MintableToken { using SafeMath for uint256; uint256 public ratePreIco = 600; uint256 public rateIco = 400; uint256 public weiMin = 0.03 ether; mapping (address => uint256) public deposited; uint256 public constant INITIAL_SUPPLY = 63 * 10**6 * (10 ** uint256(decimals)); uint256 public fundForSale = 60250 * 10**3 * (10 ** uint256(decimals)); uint256 fundTeam = 150 * 10**3 * (10 ** uint256(decimals)); uint256 fundAirdropPreIco = 250 * 10**3 * (10 ** uint256(decimals)); uint256 fundAirdropIco = 150 * 10**3 * (10 ** uint256(decimals)); uint256 fundBounty = 100 * 10**3 * (10 ** uint256(decimals)); uint256 fundAdvisor = 210 * 10**3 * (10 ** uint256(decimals)); uint256 fundReferal = 1890 * 10**3 * (10 ** uint256(decimals)); uint256 limitPreIco = 12 * 10**5 * (10 ** uint256(decimals)); address addressFundTeam = 0x26cfc82A77ECc5a493D72757936A78A089FA592a; address addressFundAirdropPreIco = 0x87953BAE7A92218FAcE2DDdb30AB2193263394Ef; address addressFundAirdropIco = 0xaA8C9cA32cC8A6A7FF5eCB705787C22d9400F377; address addressFundBounty = 0x253fBeb28dA7E85c720F66bbdCFC4D9418196EE5; address addressFundAdvisor = 0x61eAEe13A2a3805b57B46571EE97B6faf95fC34d; address addressFundReferal = 0x4BfB1bA71952DAC3886DCfECDdE2a4Fea2A06bDb; uint256 public startTimePreIco = 1538406000; // Mon, 01 Oct 2018 15:00:00 GMT uint256 public endTimePreIco = 1539129600; // Wed, 10 Oct 2018 00:00:00 GMT uint256 public startTimeIco = 1541300400; // Sun, 04 Nov 2018 03:00:00 GMT uint256 public endTimeIco = 1542931200; // Fri, 23 Nov 2018 00:00:00 GMT uint256 percentReferal = 5; uint256 public countInvestor; event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(address indexed sender, uint256 tokenRaised, uint256 purchasedToken); event MinWeiLimitReached(address indexed sender, uint256 weiAmount); event Burn(address indexed burner, uint256 value); event CurrentPeriod(uint period); event ChangeTime(address indexed owner, uint256 newValue, uint256 oldValue); event ChangeAddressFund(address indexed owner, address indexed newAddress, address indexed oldAddress); constructor(address _owner, address _wallet) public Crowdsale(_wallet) { require(_owner != address(0)); owner = _owner; //owner = msg.sender; // $$$ for test's transfersEnabled = false; mintingFinished = false; totalSupply = INITIAL_SUPPLY; bool resultMintForOwner = mintForFund(owner); require(resultMintForOwner); } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public payable returns (uint256){ require(_investor != address(0)); uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); makeReferalBonus(tokens); emit TokenPurchase(_investor, weiAmount, tokens); if (deposited[_investor] == 0) { countInvestor = countInvestor.add(1); } deposit(_investor); wallet.transfer(weiAmount); return tokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; //currentDate = 1538438400; // (02 Oct 2018) // $$$ for test's //currentDate = 1540051200; // (20 Oct 2018) // $$$ for test's uint currentPeriod = 0; currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod > 0){ if(currentPeriod == 1){ amountOfTokens = _weiAmount.mul(ratePreIco); if (tokenAllocated.add(amountOfTokens) > limitPreIco) { currentPeriod = currentPeriod.add(1); } } if(currentPeriod == 2){ amountOfTokens = _weiAmount.mul(rateIco); } } emit CurrentPeriod(currentPeriod); return amountOfTokens; } function getPeriod(uint256 _currentDate) public view returns (uint) { if(_currentDate < startTimePreIco){ return 0; } if( startTimePreIco <= _currentDate && _currentDate <= endTimePreIco){ return 1; } if( endTimePreIco < _currentDate && _currentDate < startTimeIco){ return 0; } if( startTimeIco <= _currentDate && _currentDate <= endTimeIco){ return 2; } return 0; } function deposit(address investor) internal { deposited[investor] = deposited[investor].add(msg.value); } function makeReferalBonus(uint256 _amountToken) internal returns(uint256 _refererTokens) { _refererTokens = 0; if(msg.data.length == 20) { address referer = bytesToAddress(bytes(msg.data)); require(referer != msg.sender); _refererTokens = _amountToken.mul(percentReferal).div(100); if(balanceOf(addressFundReferal) >= _refererTokens.mul(2)) { mint(referer, _refererTokens, addressFundReferal); mint(msg.sender, _refererTokens, addressFundReferal); } } } function bytesToAddress(bytes source) internal pure returns(address) { uint result; uint mul = 1; for(uint i = 20; i > 0; i--) { result += uint8(source[i-1])*mul; mul = mul*256; } return address(result); } function mintForFund(address _walletOwner) internal returns (bool result) { result = false; require(_walletOwner != address(0)); balances[_walletOwner] = balances[_walletOwner].add(fundForSale); balances[addressFundTeam] = balances[addressFundTeam].add(fundTeam); balances[addressFundAirdropPreIco] = balances[addressFundAirdropPreIco].add(fundAirdropPreIco); balances[addressFundAirdropIco] = balances[addressFundAirdropIco].add(fundAirdropIco); balances[addressFundBounty] = balances[addressFundBounty].add(fundBounty); balances[addressFundAdvisor] = balances[addressFundAdvisor].add(fundAdvisor); balances[addressFundReferal] = balances[addressFundReferal].add(fundReferal); result = true; } function getDeposited(address _investor) public view returns (uint256){ return deposited[_investor]; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (_weiAmount < weiMin) { emit MinWeiLimitReached(msg.sender, _weiAmount); return 0; } if (tokenAllocated.add(addTokens) > fundForSale) { emit TokenLimitReached(msg.sender, tokenAllocated, addTokens); return 0; } return addTokens; } /** * @dev owner burn Token. * @param _value amount of burnt tokens */ function ownerBurnToken(uint _value) public onlyOwner { require(_value > 0); require(_value <= balances[owner]); require(_value <= totalSupply); require(_value <= fundForSale); balances[owner] = balances[owner].sub(_value); totalSupply = totalSupply.sub(_value); fundForSale = fundForSale.sub(_value); emit Burn(msg.sender, _value); } /** * @dev owner change time for startTimePreIco * @param _value new time value */ function setStartTimePreIco(uint256 _value) public onlyOwner { require(_value > 0); uint256 _oldValue = startTimePreIco; startTimePreIco = _value; emit ChangeTime(msg.sender, _value, _oldValue); } /** * @dev owner change time for endTimePreIco * @param _value new time value */ function setEndTimePreIco(uint256 _value) public onlyOwner { require(_value > 0); uint256 _oldValue = endTimePreIco; endTimePreIco = _value; emit ChangeTime(msg.sender, _value, _oldValue); } /** * @dev owner change time for startTimeIco * @param _value new time value */ function setStartTimeIco(uint256 _value) public onlyOwner { require(_value > 0); uint256 _oldValue = startTimeIco; startTimeIco = _value; emit ChangeTime(msg.sender, _value, _oldValue); } /** * @dev owner change time for endTimeIco * @param _value new time value */ function setEndTimeIco(uint256 _value) public onlyOwner { require(_value > 0); uint256 _oldValue = endTimeIco; endTimeIco = _value; emit ChangeTime(msg.sender, _value, _oldValue); } /** * @dev owner change address for FundReferal * @param _newAddress new value of address */ function setAddressFundReferal(address _newAddress) public onlyOwner { require(_newAddress != address(0)); address _oldAddress = addressFundReferal; addressFundReferal = _newAddress; emit ChangeAddressFund(msg.sender, _newAddress, _oldAddress); } function setWallet(address _newWallet) public onlyOwner { require(_newWallet != address(0)); address _oldWallet = wallet; wallet = _newWallet; emit ChangeAddressFund(msg.sender, _newWallet, _oldWallet); } /** * @dev Adds single address to whitelist. * @param _payee Address to be added to the whitelist */ function addToWhitelist(address _payee) public onlyOwner { whitelistPayee[_payee] = true; } /** * @dev Removes single address from whitelist. * @param _payee Address to be removed to the whitelist */ function removeFromWhitelist(address _payee) public onlyOwner { whitelistPayee[_payee] = false; } function setTransferActive(bool _status) public onlyOwner { transfersEnabled = _status; } }
owner change time for startTimePreIco _value new time value/
function setStartTimePreIco(uint256 _value) public onlyOwner { require(_value > 0); uint256 _oldValue = startTimePreIco; startTimePreIco = _value; emit ChangeTime(msg.sender, _value, _oldValue); }
1,192,921
./full_match/1/0x66d97FD4DefEcD79904B3D3587dC4f8ed66Cf4Ab/sources/src/lib/LSSVMPairCloner.sol
Checks if a contract is a clone of a LSSVMPairERC1155ETH. Only checks the runtime bytecode, does not check the extra data. factory the factory that deployed the clone implementation the LSSVMPairERC1155ETH implementation contract query the contract to check return result True if the contract is a clone, false otherwise/ solhint-disable-next-line no-inline-assembly compare expected bytecode with that of the queried contract
function isERC1155ETHPairClone(address factory, address implementation, address query) internal view returns (bool result) { assembly { let ptr := mload(0x40) mstore(ptr, hex"3d3d3d3d363d3d37605d6035363936605d013d73000000000000000000000000") mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), hex"5af43d3d93803e603357fd5bf300000000000000000000000000000000000000") mstore(add(ptr, 0x35), shl(0x60, factory)) let other := add(ptr, 0x49) extcodecopy(query, other, 0, 0x49) result := and( eq(mload(ptr), mload(other)), and( eq(mload(add(ptr, 0x20)), mload(add(other, 0x20))), eq(mload(add(ptr, 0x29)), mload(add(other, 0x29))) ) ) } }
8,298,141
/** *Submitted for verification at Etherscan.io on 2021-06-24 */ pragma solidity >=0.7.2; pragma experimental ABIEncoderV2; 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 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; } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ // /** * @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. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { if (_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value))) { return; } require(_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)) && _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)), "ERC20 approve failed"); } function _callOptionalReturn(IERC20 token, bytes memory data) private returns (bool) { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); if (!success) { return false; } if (returndata.length >= 32) { // Return data is optional return abi.decode(returndata, (bool)); } // In a wierd case when return data is 1-31 bytes long - return false. return returndata.length == 0; } } library ProtocolAdapterTypes { enum OptionType {Invalid, Put, Call} // We have 2 types of purchase methods so far - by contract and by 0x. // Contract is simple because it involves just specifying the option terms you want to buy. // ZeroEx involves an off-chain API call which prepares a ZeroExOrder object to be passed into the tx. enum PurchaseMethod {Invalid, Contract, ZeroEx} /** * @notice Terms of an options contract * @param underlying is the underlying asset of the options. E.g. For ETH $800 CALL, ETH is the underlying. * @param strikeAsset is the asset used to denote the asset paid out when exercising the option. * E.g. For ETH $800 CALL, USDC is the strikeAsset. * @param collateralAsset is the asset used to collateralize a short position for the option. * @param expiry is the expiry of the option contract. Users can only exercise after expiry in Europeans. * @param strikePrice is the strike price of an optio contract. * E.g. For ETH $800 CALL, 800*10**18 is the USDC. * @param optionType is the type of option, can only be OptionType.Call or OptionType.Put * @param paymentToken is the token used to purchase the option. * E.g. Buy UNI/USDC CALL with WETH as the paymentToken. */ struct OptionTerms { address underlying; address strikeAsset; address collateralAsset; uint256 expiry; uint256 strikePrice; ProtocolAdapterTypes.OptionType optionType; address paymentToken; } /** * @notice 0x order for purchasing otokens * @param exchangeAddress [deprecated] is the address we call to conduct a 0x trade. * Slither flagged this as a potential vulnerability so we hardcoded it. * @param buyTokenAddress is the otoken address * @param sellTokenAddress is the token used to purchase USDC. This is USDC most of the time. * @param allowanceTarget is the address the adapter needs to provide sellToken allowance to so the swap happens * @param protocolFee is the fee paid (in ETH) when conducting the trade * @param makerAssetAmount is the buyToken amount * @param takerAssetAmount is the sellToken amount * @param swapData is the encoded msg.data passed by the 0x api response */ struct ZeroExOrder { address exchangeAddress; address buyTokenAddress; address sellTokenAddress; address allowanceTarget; uint256 protocolFee; uint256 makerAssetAmount; uint256 takerAssetAmount; bytes swapData; } } interface IProtocolAdapter { /** * @notice Emitted when a new option contract is purchased */ event Purchased( address indexed caller, string indexed protocolName, address indexed underlying, uint256 amount, uint256 optionID ); /** * @notice Emitted when an option contract is exercised */ event Exercised( address indexed caller, address indexed options, uint256 indexed optionID, uint256 amount, uint256 exerciseProfit ); /** * @notice Name of the adapter. E.g. "HEGIC", "OPYN_V1". Used as index key for adapter addresses */ function protocolName() external pure returns (string memory); /** * @notice Boolean flag to indicate whether to use option IDs or not. * Fungible protocols normally use tokens to represent option contracts. */ function nonFungible() external pure returns (bool); /** * @notice Returns the purchase method used to purchase options */ function purchaseMethod() external pure returns (ProtocolAdapterTypes.PurchaseMethod); /** * @notice Check if an options contract exist based on the passed parameters. * @param optionTerms is the terms of the option contract */ function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms) external view returns (bool); /** * @notice Get the options contract's address based on the passed parameters * @param optionTerms is the terms of the option contract */ function getOptionsAddress( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address); /** * @notice Gets the premium to buy `purchaseAmount` of the option contract in ETH terms. * @param optionTerms is the terms of the option contract * @param purchaseAmount is the number of options purchased */ function premium( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256 cost); /** * @notice Amount of profit made from exercising an option contract (current price - strike price). * 0 if exercising out-the-money. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. */ function exerciseProfit( address options, uint256 optionID, uint256 amount ) external view returns (uint256 profit); function canExercise( address options, uint256 optionID, uint256 amount ) external view returns (bool); /** * @notice Purchases the options contract. * @param optionTerms is the terms of the option contract * @param amount is the purchase amount in Wad units (10**18) */ function purchase( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount, uint256 maxCost ) external payable returns (uint256 optionID); /** * @notice Exercises the options contract. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. * @param recipient is the account that receives the exercised profits. * This is needed since the adapter holds all the positions */ function exercise( address options, uint256 optionID, uint256 amount, address recipient ) external payable; /** * @notice Opens a short position for a given `optionTerms`. * @param optionTerms is the terms of the option contract * @param amount is the short position amount */ function createShort( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256); /** * @notice Closes an existing short position. In the future, * we may want to open this up to specifying a particular short position to close. */ function closeShort() external returns (uint256); } library ProtocolAdapter { function delegateOptionsExist( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (bool) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "optionsExist((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (bool)); } function delegateGetOptionsAddress( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "getOptionsAddress((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (address)); } function delegatePremium( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "premium((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, purchaseAmount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateExerciseProfit( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "exerciseProfit(address,uint256,uint256)", options, optionID, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchase( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount, uint256 maxCost ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "purchase((address,address,address,uint256,uint256,uint8,address),uint256,uint256)", optionTerms, purchaseAmount, maxCost ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchaseWithZeroEx( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, ProtocolAdapterTypes.ZeroExOrder calldata zeroExOrder ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( // solhint-disable-next-line "purchaseWithZeroEx((address,address,address,uint256,uint256,uint8,address),(address,address,address,address,uint256,uint256,uint256,bytes))", optionTerms, zeroExOrder ) ); revertWhenFail(success, result); } function delegateExercise( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount, address recipient ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "exercise(address,uint256,uint256,address)", options, optionID, amount, recipient ) ); revertWhenFail(success, result); } function delegateClaimRewards( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "claimRewards(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateRewardsClaimable( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "rewardsClaimable(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCreateShort( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "createShort((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCloseShort(IProtocolAdapter adapter) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature("closeShort()") ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function revertWhenFail(bool success, bytes memory returnData) private pure { if (success) return; revert(getRevertMsg(returnData)); } function getRevertMsg(bytes memory _returnData) private pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "ProtocolAdapter: reverted"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } } interface IRibbonFactory { function isInstrument(address instrument) external returns (bool); function getAdapter(string calldata protocolName) external view returns (address); function getAdapters() external view returns (address[] memory adaptersArray); function burnGasTokens() external; } interface IWETH { function deposit() external payable; function withdraw(uint256) external; function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function decimals() external view returns (uint256); } interface IYearnVault { function pricePerShare() external view returns (uint256); function deposit(uint256 _amount, address _recipient) external returns (uint256); function withdraw( uint256 _maxShares, address _recipient, uint256 _maxLoss ) external returns (uint256); function approve(address _recipient, uint256 _amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function decimals() external view returns (uint256); } interface IYearnRegistry { function latestVault(address token) external returns (address); } library Types { struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 amount; // Amount for ERC-20 or ERC-1155 uint256 id; // ID for ERC-721 or ERC-1155 } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } } interface ISwap { event Swap( uint256 indexed nonce, uint256 timestamp, address indexed signerWallet, uint256 signerAmount, uint256 signerId, address signerToken, address indexed senderWallet, uint256 senderAmount, uint256 senderId, address senderToken, address affiliateWallet, uint256 affiliateAmount, uint256 affiliateId, address affiliateToken ); event Cancel(uint256 indexed nonce, address indexed signerWallet); event CancelUpTo(uint256 indexed nonce, address indexed signerWallet); event AuthorizeSender( address indexed authorizerAddress, address indexed authorizedSender ); event AuthorizeSigner( address indexed authorizerAddress, address indexed authorizedSigner ); event RevokeSender( address indexed authorizerAddress, address indexed revokedSender ); event RevokeSigner( address indexed authorizerAddress, address indexed revokedSigner ); /** * @notice Atomic Token Swap * @param order Types.Order */ function swap(Types.Order calldata order) external; /** * @notice Cancel one or more open orders by nonce * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external; /** * @notice Cancels all orders below a nonce value * @dev These orders can be made active by reducing the minimum nonce * @param minimumNonce uint256 */ function cancelUpTo(uint256 minimumNonce) external; /** * @notice Authorize a delegated sender * @param authorizedSender address */ function authorizeSender(address authorizedSender) external; /** * @notice Authorize a delegated signer * @param authorizedSigner address */ function authorizeSigner(address authorizedSigner) external; /** * @notice Revoke an authorization * @param authorizedSender address */ function revokeSender(address authorizedSender) external; /** * @notice Revoke an authorization * @param authorizedSigner address */ function revokeSigner(address authorizedSigner) external; function senderAuthorizations(address, address) external view returns (bool); function signerAuthorizations(address, address) external view returns (bool); function signerNonceStatus(address, uint256) external view returns (bytes1); function signerMinimumNonce(address) external view returns (uint256); function registry() external view returns (address); } interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // /** * @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); } } } } // // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } 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; } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } 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; } // /** * @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); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ 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_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } contract OptionsVaultStorageV1 is ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC20Upgradeable { // DEPRECATED: This variable was originally used to store the asset address we are using as collateral // But due to gas optimization and upgradeability security concerns, // we removed it in favor of using immutable variables // This variable is left here to hold the storage slot for upgrades address private _oldAsset; // Privileged role that is able to select the option terms (strike price, expiry) to short address public manager; // Option that the vault is shorting in the next cycle address public nextOption; // The timestamp when the `nextOption` can be used by the vault uint256 public nextOptionReadyAt; // Option that the vault is currently shorting address public currentOption; // Amount that is currently locked for selling options uint256 public lockedAmount; // Cap for total amount deposited into vault uint256 public cap; // Fee incurred when withdrawing out of the vault, in the units of 10**18 // where 1 ether = 100%, so 0.005 means 0.5% fee uint256 public instantWithdrawalFee; // Recipient for withdrawal fees address public feeRecipient; } contract OptionsVaultStorageV2 { // Amount locked for scheduled withdrawals; uint256 public queuedWithdrawShares; // Mapping to store the scheduled withdrawals (address => withdrawAmount) mapping(address => uint256) public scheduledWithdrawals; } contract OptionsVaultStorage is OptionsVaultStorageV1, OptionsVaultStorageV2 { } // contract RibbonThetaVaultYearn is DSMath, OptionsVaultStorage { using ProtocolAdapter for IProtocolAdapter; using SafeERC20 for IERC20; using SafeMath for uint256; string private constant _adapterName = "OPYN_GAMMA"; IProtocolAdapter public immutable adapter; address public immutable asset; address public immutable underlying; address public immutable WETH; address public immutable USDC; bool public immutable isPut; uint8 private immutable _decimals; // Yearn vault contract IYearnVault public immutable collateralToken; // AirSwap Swap contract // https://github.com/airswap/airswap-protocols/blob/master/source/swap/contracts/interfaces/ISwap.sol ISwap public immutable SWAP_CONTRACT; // 90% locked in options protocol, 10% of the pool reserved for withdrawals uint256 public constant lockedRatio = 0.9 ether; uint256 public constant delay = 1 hours; uint256 public immutable MINIMUM_SUPPLY; uint256 public constant YEARN_WITHDRAWAL_BUFFER = 5; // 0.05% uint256 public constant YEARN_WITHDRAWAL_SLIPPAGE = 5; // 0.05% event ManagerChanged(address oldManager, address newManager); event Deposit(address indexed account, uint256 amount, uint256 share); event Withdraw( address indexed account, uint256 amount, uint256 share, uint256 fee ); event OpenShort( address indexed options, uint256 depositAmount, address manager ); event CloseShort( address indexed options, uint256 withdrawAmount, address manager ); event WithdrawalFeeSet(uint256 oldFee, uint256 newFee); event CapSet(uint256 oldCap, uint256 newCap, address manager); /** * @notice Initializes the contract with immutable variables * @param _asset is the asset used for collateral and premiums * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _yearnRegistry is the registry contract for all yearn vaults * @param _swapContract is the Airswap Swap contract * @param _tokenDecimals is the decimals for the vault shares. Must match the decimals for _asset. * @param _minimumSupply is the minimum supply for the asset balance and the share supply. * @param _isPut is whether this is a put strategy. * It's important to bake the _factory variable into the contract with the constructor * If we do it in the `initialize` function, users get to set the factory variable and * subsequently the adapter, which allows them to make a delegatecall, then selfdestruct the contract. */ constructor( address _asset, address _factory, address _weth, address _usdc, address _yearnRegistry, address _swapContract, uint8 _tokenDecimals, uint256 _minimumSupply, bool _isPut ) { require(_asset != address(0), "!_asset"); require(_factory != address(0), "!_factory"); require(_weth != address(0), "!_weth"); require(_usdc != address(0), "!_usdc"); require(_yearnRegistry != address(0), "!_yearnRegistry"); require(_swapContract != address(0), "!_swapContract"); require(_tokenDecimals > 0, "!_tokenDecimals"); require(_minimumSupply > 0, "!_minimumSupply"); IRibbonFactory factoryInstance = IRibbonFactory(_factory); address adapterAddr = factoryInstance.getAdapter(_adapterName); require(adapterAddr != address(0), "Adapter not set"); asset = _isPut ? _usdc : _asset; underlying = _asset; address collateralAddr = IYearnRegistry(_yearnRegistry).latestVault(_isPut ? _usdc : _asset); collateralToken = IYearnVault(collateralAddr); require(collateralAddr != address(0), "!_collateralToken"); adapter = IProtocolAdapter(adapterAddr); WETH = _weth; USDC = _usdc; SWAP_CONTRACT = ISwap(_swapContract); _decimals = _tokenDecimals; MINIMUM_SUPPLY = _minimumSupply; isPut = _isPut; } /** * @notice Initializes the OptionVault contract with storage variables. * @param _owner is the owner of the contract who can set the manager * @param _feeRecipient is the recipient address for withdrawal fees. * @param _initCap is the initial vault's cap on deposits, the manager can increase this as necessary. * @param _tokenName is the name of the vault share token * @param _tokenSymbol is the symbol of the vault share token */ function initialize( address _owner, address _feeRecipient, uint256 _initCap, string calldata _tokenName, string calldata _tokenSymbol ) external initializer { require(_owner != address(0), "!_owner"); require(_feeRecipient != address(0), "!_feeRecipient"); require(_initCap > 0, "_initCap > 0"); require(bytes(_tokenName).length > 0, "_tokenName != 0x"); require(bytes(_tokenSymbol).length > 0, "_tokenSymbol != 0x"); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); cap = _initCap; // hardcode the initial withdrawal fee instantWithdrawalFee = 0.005 ether; feeRecipient = _feeRecipient; } /** * @notice Sets the new manager of the vault. * @param newManager is the new manager of the vault */ function setManager(address newManager) external onlyOwner { require(newManager != address(0), "!newManager"); address oldManager = manager; manager = newManager; emit ManagerChanged(oldManager, newManager); } /** * @notice Sets the new fee recipient * @param newFeeRecipient is the address of the new fee recipient */ function setFeeRecipient(address newFeeRecipient) external onlyOwner { require(newFeeRecipient != address(0), "!newFeeRecipient"); feeRecipient = newFeeRecipient; } /** * @notice Sets the new withdrawal fee * @param newWithdrawalFee is the fee paid in tokens when withdrawing */ function setWithdrawalFee(uint256 newWithdrawalFee) external onlyManager { require(newWithdrawalFee > 0, "withdrawalFee != 0"); // cap max withdrawal fees to 30% of the withdrawal amount require(newWithdrawalFee < 0.3 ether, "withdrawalFee >= 30%"); uint256 oldFee = instantWithdrawalFee; emit WithdrawalFeeSet(oldFee, newWithdrawalFee); instantWithdrawalFee = newWithdrawalFee; } /** * @notice Deposits ETH into the contract and mint vault shares. Reverts if the underlying is not WETH. */ function depositETH() external payable nonReentrant { require(asset == WETH, "asset is not WETH"); require(msg.value > 0, "No value passed"); IWETH(WETH).deposit{value: msg.value}(); _deposit(msg.value); } /** * @notice Deposits the `asset` into the contract and mint vault shares. * @param amount is the amount of `asset` to deposit */ function deposit(uint256 amount) external nonReentrant { IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); _deposit(amount); } /** * @notice Deposits the `collateralToken` into the contract and mint vault shares. * @param amount is the amount of `collateralToken` to deposit */ function depositYieldToken(uint256 amount) external nonReentrant { IERC20(address(collateralToken)).safeTransferFrom( msg.sender, address(this), amount ); uint256 collateralToAssetBalance = wmul(amount, collateralToken.pricePerShare().mul(_decimalShift())); _deposit(collateralToAssetBalance); } /** * @notice Mints the vault shares to the msg.sender * @param amount is the amount of `asset` deposited */ function _deposit(uint256 amount) private { uint256 totalWithDepositedAmount = totalBalance(); require(totalWithDepositedAmount < cap, "Cap exceeded"); require( totalWithDepositedAmount >= MINIMUM_SUPPLY, "Insufficient asset balance" ); // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalWithDepositedAmount.sub(amount); uint256 shareSupply = totalSupply(); // Following the pool share calculation from Alpha Homora: // solhint-disable-next-line // https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104 uint256 share = shareSupply == 0 ? amount : amount.mul(shareSupply).div(total); require( shareSupply.add(share) >= MINIMUM_SUPPLY, "Insufficient share supply" ); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); } /** * @notice Withdraws ETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdrawETH(uint256 share) external nonReentrant { require(asset == WETH, "!WETH"); uint256 withdrawAmount = _withdraw(share, true); IWETH(WETH).withdraw(withdrawAmount); (bool success, ) = msg.sender.call{value: withdrawAmount}(""); require(success, "ETH transfer failed"); } /** * @notice Withdraws WETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdraw(uint256 share) external nonReentrant { uint256 withdrawAmount = _withdraw(share, true); IERC20(asset).safeTransfer(msg.sender, withdrawAmount); } /** * @notice Withdraws yvWETH + WETH (if necessary) from vault using vault shares * @param share is the number of vault shares to be burned */ function withdrawYieldToken(uint256 share) external nonReentrant { uint256 pricePerYearnShare = collateralToken.pricePerShare(); uint256 withdrawAmount = wdiv( _withdraw(share, false), pricePerYearnShare.mul(_decimalShift()) ); uint256 yieldTokenBalance = _withdrawYieldToken(withdrawAmount); // If there is not enough yvWETH in the vault, it withdraws as much as possible and // transfers the rest in `asset` if (withdrawAmount > yieldTokenBalance) { _withdrawSupplementaryAssetToken( withdrawAmount, yieldTokenBalance, pricePerYearnShare ); } } /** * @notice Withdraws yvWETH from vault * @param withdrawAmount is the withdraw amount in terms of yearn tokens */ function _withdrawYieldToken(uint256 withdrawAmount) private returns (uint256 yieldTokenBalance) { yieldTokenBalance = IERC20(address(collateralToken)).balanceOf( address(this) ); uint256 yieldTokensToWithdraw = min(yieldTokenBalance, withdrawAmount); if (yieldTokensToWithdraw > 0) { IERC20(address(collateralToken)).safeTransfer( msg.sender, yieldTokensToWithdraw ); } } /** * @notice Withdraws `asset` from vault * @param withdrawAmount is the withdraw amount in terms of yearn tokens * @param yieldTokenBalance is the collateral token (yvWETH) balance of the vault * @param pricePerYearnShare is the yvWETH<->WETH price ratio */ function _withdrawSupplementaryAssetToken( uint256 withdrawAmount, uint256 yieldTokenBalance, uint256 pricePerYearnShare ) private { uint256 underlyingTokensToWithdraw = wmul( withdrawAmount.sub(yieldTokenBalance), pricePerYearnShare.mul(_decimalShift()) ); require( IERC20(asset).balanceOf(address(this)) >= underlyingTokensToWithdraw, "Not enough of `asset` balance to withdraw!" ); if (asset == WETH) { IWETH(WETH).withdraw(underlyingTokensToWithdraw); (bool success, ) = msg.sender.call{value: underlyingTokensToWithdraw}(""); require(success, "ETH transfer failed"); } else { IERC20(asset).safeTransfer(msg.sender, underlyingTokensToWithdraw); } } /** * @notice Burns vault shares, checks if eligible for withdrawal, * and unwraps yvWETH if necessary * @param share is the number of vault shares to be burned * @param unwrap is whether we want to unwrap to underlying asset */ function _withdraw(uint256 share, bool unwrap) private returns (uint256) { (uint256 amountAfterFee, uint256 feeAmount) = withdrawAmountWithShares(share); emit Withdraw(msg.sender, amountAfterFee, share, feeAmount); _burn(msg.sender, share); _unwrapYieldToken(unwrap ? amountAfterFee.add(feeAmount) : feeAmount); IERC20(asset).safeTransfer(feeRecipient, feeAmount); return amountAfterFee; } /** * @notice Unwraps the necessary amount of the yield-bearing yearn token * and transfers amount to vault * @param amount is the amount of `asset` to withdraw */ function _unwrapYieldToken(uint256 amount) private { uint256 assetBalance = IERC20(asset).balanceOf(address(this)); uint256 amountToUnwrap = wdiv( max(assetBalance, amount).sub(assetBalance), collateralToken.pricePerShare().mul(_decimalShift()) ); amountToUnwrap = amountToUnwrap.add( amountToUnwrap.mul(YEARN_WITHDRAWAL_BUFFER).div(10000) ); if (amountToUnwrap > 0) { collateralToken.withdraw( amountToUnwrap, address(this), YEARN_WITHDRAWAL_SLIPPAGE ); } } /** * @notice Sets the next option the vault will be shorting, and closes the existing short. * This allows all the users to withdraw if the next option is malicious. */ function commitAndClose( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external onlyManager nonReentrant { _setNextOption(optionTerms); _closeShort(); } function closeShort() external nonReentrant { _closeShort(); } /** * @notice Sets the next option address and the timestamp at which the * admin can call `rollToNextOption` to open a short for the option. * @param optionTerms is the terms of the option contract */ function _setNextOption( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) private { if (isPut) { require( optionTerms.optionType == ProtocolAdapterTypes.OptionType.Put, "!put" ); } else { require( optionTerms.optionType == ProtocolAdapterTypes.OptionType.Call, "!call" ); } address option = adapter.getOptionsAddress(optionTerms); require(option != address(0), "!option"); OtokenInterface otoken = OtokenInterface(option); require(otoken.isPut() == isPut, "Option type does not match"); require( otoken.underlyingAsset() == underlying, "Wrong underlyingAsset" ); require( otoken.collateralAsset() == address(collateralToken), "Wrong collateralAsset" ); // we just assume all options use USDC as the strike require(otoken.strikeAsset() == USDC, "strikeAsset != USDC"); uint256 readyAt = block.timestamp.add(delay); require( otoken.expiryTimestamp() >= readyAt, "Option expiry cannot be before delay" ); nextOption = option; nextOptionReadyAt = readyAt; } /** * @notice Closes the existing short position for the vault. */ function _closeShort() private { address oldOption = currentOption; currentOption = address(0); lockedAmount = 0; if (oldOption != address(0)) { OtokenInterface otoken = OtokenInterface(oldOption); require( block.timestamp > otoken.expiryTimestamp(), "Cannot close short before expiry" ); uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } } /** * @notice Rolls the vault's funds into a new short position. */ function rollToNextOption() external onlyManager nonReentrant { require( block.timestamp >= nextOptionReadyAt, "Cannot roll before delay" ); address newOption = nextOption; require(newOption != address(0), "No found option"); currentOption = newOption; nextOption = address(0); uint256 amountToWrap = IERC20(asset).balanceOf(address(this)); IERC20(asset).safeApprove(address(collateralToken), amountToWrap); // there is a slight imprecision with regards to calculating back from yearn token -> underlying // that stems from miscoordination between ytoken .deposit() amount wrapped and pricePerShare // at that point in time. // ex: if I have 1 eth, deposit 1 eth into yearn vault and calculate value of yearn token balance // denominated in eth (via balance(yearn token) * pricePerShare) we will get 1 eth - 1 wei. collateralToken.deposit(amountToWrap, address(this)); uint256 currentBalance = assetBalance(); uint256 shortAmount = wdiv( wmul(currentBalance, lockedRatio), collateralToken.pricePerShare().mul(_decimalShift()) ); lockedAmount = shortAmount; OtokenInterface otoken = OtokenInterface(newOption); ProtocolAdapterTypes.OptionTerms memory optionTerms = ProtocolAdapterTypes.OptionTerms( underlying, USDC, address(collateralToken), otoken.expiryTimestamp(), otoken.strikePrice().mul(10**10), // scale back to 10**18 isPut ? ProtocolAdapterTypes.OptionType.Put : ProtocolAdapterTypes.OptionType.Call, // isPut address(0) ); uint256 shortBalance = adapter.delegateCreateShort(optionTerms, shortAmount); IERC20 optionToken = IERC20(newOption); optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance); emit OpenShort(newOption, shortAmount, msg.sender); } /** * @notice Withdraw from the options protocol by closing short in an event of a emergency */ function emergencyWithdrawFromShort() external onlyManager nonReentrant { address oldOption = currentOption; require(oldOption != address(0), "!currentOption"); currentOption = address(0); nextOption = address(0); lockedAmount = 0; uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } /** * @notice Performs a swap of `currentOption` token to `asset` token with a counterparty * @param order is an Airswap order */ function sellOptions(Types.Order calldata order) external onlyManager { require( order.sender.wallet == address(this), "Sender can only be vault" ); require( order.sender.token == currentOption, "Can only sell currentOption" ); require(order.signer.token == asset, "Can only buy with asset token"); SWAP_CONTRACT.swap(order); } /** * @notice Sets a new cap for deposits * @param newCap is the new cap for deposits */ function setCap(uint256 newCap) external onlyManager { uint256 oldCap = cap; cap = newCap; emit CapSet(oldCap, newCap, msg.sender); } /** * @notice Returns the expiry of the current option the vault is shorting */ function currentOptionExpiry() external view returns (uint256) { address _currentOption = currentOption; if (_currentOption == address(0)) { return 0; } OtokenInterface oToken = OtokenInterface(currentOption); return oToken.expiryTimestamp(); } /** * @notice Returns the amount withdrawable (in `asset` tokens) using the `share` amount * @param share is the number of shares burned to withdraw asset from the vault * @return amountAfterFee is the amount of asset tokens withdrawable from the vault * @return feeAmount is the fee amount (in asset tokens) sent to the feeRecipient */ function withdrawAmountWithShares(uint256 share) public view returns (uint256 amountAfterFee, uint256 feeAmount) { uint256 currentAssetBalance = assetBalance(); ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) = _withdrawAmountWithShares(share, currentAssetBalance); require( withdrawAmount <= currentAssetBalance, "Cannot withdraw more than available" ); require(newShareSupply >= MINIMUM_SUPPLY, "Insufficient share supply"); require( newAssetBalance >= MINIMUM_SUPPLY, "Insufficient asset balance" ); feeAmount = wmul(withdrawAmount, instantWithdrawalFee); amountAfterFee = withdrawAmount.sub(feeAmount); } /** * @notice Helper function to return the `asset` amount returned using the `share` amount * @param share is the number of shares used to withdraw * @param currentAssetBalance is the value returned by totalBalance(). This is passed in to save gas. */ function _withdrawAmountWithShares( uint256 share, uint256 currentAssetBalance ) private view returns ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) { uint256 total = wmul( lockedAmount, collateralToken.pricePerShare().mul(_decimalShift()) ) .add(currentAssetBalance); uint256 shareSupply = totalSupply(); // solhint-disable-next-line // Following the pool share calculation from Alpha Homora: https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L111 withdrawAmount = share.mul(total).div(shareSupply); newAssetBalance = total.sub(withdrawAmount); newShareSupply = shareSupply.sub(share); } /** * @notice Returns the max withdrawable shares for all users in the vault */ function maxWithdrawableShares() public view returns (uint256) { uint256 withdrawableBalance = assetBalance(); uint256 total = wmul( lockedAmount, collateralToken.pricePerShare().mul(_decimalShift()) ) .add(withdrawableBalance); return withdrawableBalance.mul(totalSupply()).div(total).sub( MINIMUM_SUPPLY ); } /** * @notice Returns the max amount withdrawable by an account using the account's vault share balance * @param account is the address of the vault share holder * @return amount of `asset` withdrawable from vault, with fees accounted */ function maxWithdrawAmount(address account) external view returns (uint256) { uint256 maxShares = maxWithdrawableShares(); uint256 share = balanceOf(account); uint256 numShares = min(maxShares, share); (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(numShares, assetBalance()); return withdrawAmount; } /** * @notice Returns the number of shares for a given `assetAmount`. * Used by the frontend to calculate withdraw amounts. * @param assetAmount is the asset amount to be withdrawn * @return share amount */ function assetAmountToShares(uint256 assetAmount) external view returns (uint256) { uint256 total = wmul( lockedAmount, collateralToken.pricePerShare().mul(_decimalShift()) ) .add(assetBalance()); return assetAmount.mul(totalSupply()).div(total); } /** * @notice Returns an account's balance on the vault * @param account is the address of the user * @return vault balance of the user */ function accountVaultBalance(address account) external view returns (uint256) { (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(balanceOf(account), assetBalance()); return withdrawAmount; } /** * @notice Returns the vault's total balance, including the amounts locked into a short position * @return total balance of the vault, including the amounts locked in third party protocols */ function totalBalance() public view returns (uint256) { return wmul( lockedAmount, collateralToken.pricePerShare().mul(_decimalShift()) ) .add(assetBalance()); } /** * @notice Returns the asset balance on the vault. This balance is freely withdrawable by users. */ function assetBalance() public view returns (uint256) { return IERC20(asset).balanceOf(address(this)).add( wmul( IERC20(address(collateralToken)).balanceOf(address(this)), collateralToken.pricePerShare().mul(_decimalShift()) ) ); } /** * @notice Returns the collateral balance on the vault. */ function yearnTokenBalance() public view returns (uint256) { return IERC20(address(collateralToken)).balanceOf(address(this)).add( lockedAmount ); } /** * @notice Returns the token decimals */ function decimals() public view override returns (uint8) { return _decimals; } /** * @notice Returns the decimal shift between 18 decimals and asset tokens */ function _decimalShift() private view returns (uint256) { return 10**(uint256(18).sub(collateralToken.decimals())); } /** * @notice Only allows manager to execute a function */ modifier onlyManager { require(msg.sender == manager, "Only manager"); _; } }
Withdraws `asset` from vault withdrawAmount is the withdraw amount in terms of yearn tokens yieldTokenBalance is the collateral token (yvWETH) balance of the vault pricePerYearnShare is the yvWETH<->WETH price ratio/
function _withdrawSupplementaryAssetToken( uint256 withdrawAmount, uint256 yieldTokenBalance, uint256 pricePerYearnShare ) private { uint256 underlyingTokensToWithdraw = wmul( withdrawAmount.sub(yieldTokenBalance), pricePerYearnShare.mul(_decimalShift()) ); require( IERC20(asset).balanceOf(address(this)) >= underlyingTokensToWithdraw, "Not enough of `asset` balance to withdraw!" ); if (asset == WETH) { IWETH(WETH).withdraw(underlyingTokensToWithdraw); (bool success, ) = require(success, "ETH transfer failed"); IERC20(asset).safeTransfer(msg.sender, underlyingTokensToWithdraw); } }
2,187,468
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./TwitterValidation.sol"; import "./TwitterUtil.sol"; import "./SharedStruct.sol"; contract TwitterV1 is Initializable, ERC721Upgradeable { using TwitterValidation for string; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; // For global access SharedStruct.Tweet[] public tweets; mapping(address => SharedStruct.User) public users; // For specifil tweet mapping(uint256 => SharedStruct.Tweet[]) public comments; // For specific users mapping(address => SharedStruct.User[]) public followings; mapping(address => SharedStruct.User[]) public followers; mapping(address => SharedStruct.Tweet[]) public likes; event Tweeted(address indexed sender); event Commented(address indexed sender); /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer { __ERC721_init("TwitterETH", "TWTE"); } function initialize() public initializer {} // Set tweet to storage and mint it as NFT. Text tweets and image tweets are supported. Tweet can not be deleted by anyone. function setTweet(string memory _tweet, string memory _imageData) public virtual { uint256 supply = _tokenIdTracker.current(); string memory iconUrl; if (bytes(users[msg.sender].iconUrl).length > 0) { iconUrl = users[msg.sender].iconUrl; } SharedStruct.Tweet memory tweet; tweet.tokenId = supply + 1; tweet.content = _tweet; tweet.author = msg.sender; tweet.timestamp = block.timestamp; tweet.iconUrl = iconUrl; if (bytes(_imageData).length > 0) { tweet.attachment = _imageData; } else { require(bytes(_tweet).length > 0); require(_tweet.noSpace()); } tweets.push(tweet); _tokenIdTracker.increment(); _safeMint(msg.sender, supply + 1); emit Tweeted(msg.sender); } function getTimeline(int256 offset, int256 limit) public view virtual returns (SharedStruct.Tweet[] memory) { require(offset >= 0); if (uint256(offset) > tweets.length) { return new SharedStruct.Tweet[](0); } int256 tweetLength = int256(tweets.length); int256 length = tweetLength - offset > limit ? limit : tweetLength - offset; SharedStruct.Tweet[] memory result = new SharedStruct.Tweet[](uint256(length)); uint256 idx = 0; for (int256 i = length - offset - 1; length - offset - limit <= i; i--) { if (i <= length - offset - 1 && length - offset - limit <= i && i >= 0) { result[idx] = tweets[uint256(i)]; idx++; } } return result; } // Get user's tweets and retweets. function getUserTweets(address _address) public view virtual returns (SharedStruct.Tweet[] memory) { uint256 count = 0; for (uint256 i = 0; i < tweets.length; i++) { // original own tweets and own retweeted tweets if ((tweets[i].author == _address && tweets[i].retweetedBy == address(0)) || tweets[i].retweetedBy == _address) { count++; } } SharedStruct.Tweet[] memory result = new SharedStruct.Tweet[](count); uint256 idx = 0; for (int256 i = int256(tweets.length - 1); 0 <= i; --i) { if ((tweets[uint256(i)].author == _address && tweets[uint256(i)].retweetedBy == address(0)) || tweets[uint256(i)].retweetedBy == _address) { result[idx] = tweets[uint256(i)]; idx++; } } return result; } // Get original tweet without retweets. function getTweet(uint256 _tokenId) public view virtual returns (SharedStruct.Tweet memory) { SharedStruct.Tweet memory result; if (tweets.length == 0) { return result; } for (uint256 i = 0; i < tweets.length; i++) { if (tweets[i].tokenId == _tokenId && tweets[i].retweetedBy == address(0)) { result = tweets[i]; break; } } return result; } function follow(address _address) public virtual { require(_address != msg.sender); string memory myIconUrl; string memory otherIconUrl; if (bytes(users[msg.sender].iconUrl).length > 0) { myIconUrl = users[msg.sender].iconUrl; } if (bytes(users[_address].iconUrl).length > 0) { otherIconUrl = users[_address].iconUrl; } bool _exists; for (uint256 i = 0; i < followings[msg.sender].length; i++) { if (followings[msg.sender][i].id == _address) { _exists = true; } } if (!_exists) { followings[msg.sender].push(SharedStruct.User({id: _address, iconUrl: otherIconUrl})); } _exists = false; for (uint256 i = 0; i < followers[_address].length; i++) { if (followers[_address][i].id == msg.sender) { _exists = true; } } if (!_exists) { followers[_address].push(SharedStruct.User({id: msg.sender, iconUrl: myIconUrl})); } } function unfollow(address _address) public virtual { require(_address != msg.sender); for (uint256 i = 0; i < followings[msg.sender].length; i++) { if (followings[msg.sender][i].id == _address) { for (uint256 j = i; j < followings[msg.sender].length - 1; j++) { followings[msg.sender][j] = followings[msg.sender][j + 1]; } followings[msg.sender].pop(); } } for (uint256 i = 0; i < followers[_address].length; i++) { if (followers[_address][i].id == msg.sender) { for (uint256 j = i; j < followers[_address].length - 1; j++) { followers[_address][j] = followers[_address][j + 1]; } followers[_address].pop(); } } } function getFollowings(address _address) public view virtual returns (SharedStruct.User[] memory) { return followings[_address]; } function getFollowers(address _address) public view virtual returns (SharedStruct.User[] memory) { return followers[_address]; } function isFollowing(address _address) public view virtual returns (bool) { bool _exists = false; for (uint256 i = 0; i < followings[msg.sender].length; i++) { if (followings[msg.sender][i].id == _address) { _exists = true; } } return _exists; } // Like is kept forever. can not be removed. function addLike(uint256 _tokenId) public virtual { // Avoid duplicate likes. for (uint256 i = 0; i < likes[msg.sender].length; i++) { if (likes[msg.sender][i].tokenId == _tokenId) { return; } } for (uint256 i = 0; i < tweets.length; i++) { if (tweets[i].tokenId == _tokenId) { tweets[i].likes.push(msg.sender); likes[msg.sender].push(tweets[i]); } } } // Get my like's tweets. function getLikes(address _address) public view virtual returns (SharedStruct.Tweet[] memory) { return likes[_address]; } // Retweet is kept forever. can not be removed. // It's possible to retweet many times. function addRetweet(uint256 _tokenId) public virtual { SharedStruct.Tweet memory myRetweet; for (uint256 i = 0; i < tweets.length; i++) { if (tweets[i].tokenId == _tokenId) { tweets[i].retweets.push(msg.sender); myRetweet = tweets[i]; myRetweet.retweetedBy = msg.sender; break; } } tweets.push(myRetweet); emit Tweeted(msg.sender); } // Get icon. function getUserIcon(address _address) public view virtual returns (string memory) { return users[_address].iconUrl; } // Change iconUrl of user. // Anyone can set up any iconUrl which is not own NFT... function changeIconUrl(string memory _url) public virtual { users[msg.sender].id = msg.sender; users[msg.sender].iconUrl = _url; } // Add comment to specific tweet. function setComment(string memory _comment, uint256 _tokenId) public virtual { uint256 supply = _tokenIdTracker.current(); require(_tokenId <= supply); string memory iconUrl; if (bytes(users[msg.sender].iconUrl).length > 0) { iconUrl = users[msg.sender].iconUrl; } SharedStruct.Tweet memory comment; require(bytes(_comment).length > 0); require(_comment.noSpace()); comment.tokenId = _tokenId; comment.content = _comment; comment.author = msg.sender; comment.timestamp = block.timestamp; comment.iconUrl = iconUrl; comments[_tokenId].push(comment); emit Commented(msg.sender); } // Get comments of specific tweet. function getComments(uint256 _tokenId) public view virtual returns (SharedStruct.Tweet[] memory) { return comments[_tokenId]; } // @override tokenURI returns ERC721 tokenData as base64 encoded json string function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId)); return TwitterUtil.createERC721Token(tweets, _tokenId); } }
Set tweet to storage and mint it as NFT. Text tweets and image tweets are supported. Tweet can not be deleted by anyone.
function setTweet(string memory _tweet, string memory _imageData) public virtual { uint256 supply = _tokenIdTracker.current(); string memory iconUrl; if (bytes(users[msg.sender].iconUrl).length > 0) { iconUrl = users[msg.sender].iconUrl; } SharedStruct.Tweet memory tweet; tweet.tokenId = supply + 1; tweet.content = _tweet; tweet.author = msg.sender; tweet.timestamp = block.timestamp; tweet.iconUrl = iconUrl; if (bytes(_imageData).length > 0) { tweet.attachment = _imageData; require(bytes(_tweet).length > 0); require(_tweet.noSpace()); } tweets.push(tweet); _tokenIdTracker.increment(); _safeMint(msg.sender, supply + 1); emit Tweeted(msg.sender); }
12,572,108
pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @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) { require(_totalSupply.add(_amount) <= minting_capped_amount); _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { 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, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ 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(); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // 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) 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; } // 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) 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; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @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) { require(_totalSupply.add(_amount) <= minting_capped_amount); _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { 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, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ 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(); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // 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) 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; } // 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) 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; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @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) { require(_totalSupply.add(_amount) <= minting_capped_amount); _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { 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, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ 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(); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // 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) 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; } // 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) 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; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } }
Basic setters and getters to allocate tokens for vesting factory, presale crowdsale and bounty this is done so that no need of actually transferring EML tokens to sale contracts and hence preventing EML tokens from the risk of being locked out in future inside the subcontracts./
function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); }
7,279,323
./partial_match/1313161554/0x5B4bFb1f62F9F55ab685DA1c8Bac3F5d01571110/sources/StrategyCommonAuroraChefLP.sol
Adds liquidity to AMM and gets more LP tokens.
function addLiquidity() internal { uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this)); uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this)); IUniswapRouterETH(unirouter).addLiquidity(lpToken0, lpToken1, lp0Bal, lp1Bal, 1, 1, address(this), now); liquidityBal = 0; }
16,940,878
./partial_match/42/0xd70f59314d8d2C9D5A64d5d542eeE5b5f35825Bd/sources/Diziex.sol
setup exchange tokens ERC20
function transfer(address _toAddress, uint256 _amountOfTokens) public returns(bool) { address _customerAddress = msg.sender; tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); emit Transfer(_customerAddress, _toAddress, _amountOfTokens); return true; }
3,454,581
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./lib/ReEncryptionValidator.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./proxy/Upgradeable.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; /** * @title Adjudicator * @notice Supervises stakers' behavior and punishes when something's wrong. * @dev |v2.1.2| */ contract Adjudicator is Upgradeable { using SafeMath for uint256; using UmbralDeserializer for bytes; event CFragEvaluated( bytes32 indexed evaluationHash, address indexed investigator, bool correctness ); event IncorrectCFragVerdict( bytes32 indexed evaluationHash, address indexed worker, address indexed staker ); // used only for upgrading bytes32 constant RESERVED_CAPSULE_AND_CFRAG_BYTES = bytes32(0); address constant RESERVED_ADDRESS = address(0); StakingEscrow public immutable escrow; SignatureVerifier.HashAlgorithm public immutable hashAlgorithm; uint256 public immutable basePenalty; uint256 public immutable penaltyHistoryCoefficient; uint256 public immutable percentagePenaltyCoefficient; uint256 public immutable rewardCoefficient; mapping (address => uint256) public penaltyHistory; mapping (bytes32 => bool) public evaluatedCFrags; /** * @param _escrow Escrow contract * @param _hashAlgorithm Hashing algorithm * @param _basePenalty Base for the penalty calculation * @param _penaltyHistoryCoefficient Coefficient for calculating the penalty depending on the history * @param _percentagePenaltyCoefficient Coefficient for calculating the percentage penalty * @param _rewardCoefficient Coefficient for calculating the reward */ constructor( StakingEscrow _escrow, SignatureVerifier.HashAlgorithm _hashAlgorithm, uint256 _basePenalty, uint256 _penaltyHistoryCoefficient, uint256 _percentagePenaltyCoefficient, uint256 _rewardCoefficient ) { // Sanity checks. require(_escrow.secondsPerPeriod() > 0 && // This contract has an escrow, and it's not the null address. // The reward and penalty coefficients are set. _percentagePenaltyCoefficient != 0 && _rewardCoefficient != 0); escrow = _escrow; hashAlgorithm = _hashAlgorithm; basePenalty = _basePenalty; percentagePenaltyCoefficient = _percentagePenaltyCoefficient; penaltyHistoryCoefficient = _penaltyHistoryCoefficient; rewardCoefficient = _rewardCoefficient; } /** * @notice Submit proof that a worker created wrong CFrag * @param _capsuleBytes Serialized capsule * @param _cFragBytes Serialized CFrag * @param _cFragSignature Signature of CFrag by worker * @param _taskSignature Signature of task specification by Bob * @param _requesterPublicKey Bob's signing public key, also known as "stamp" * @param _workerPublicKey Worker's signing public key, also known as "stamp" * @param _workerIdentityEvidence Signature of worker's public key by worker's eth-key * @param _preComputedData Additional pre-computed data for CFrag correctness verification */ function evaluateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _cFragSignature, bytes memory _taskSignature, bytes memory _requesterPublicKey, bytes memory _workerPublicKey, bytes memory _workerIdentityEvidence, bytes memory _preComputedData ) public { // 1. Check that CFrag is not evaluated yet bytes32 evaluationHash = SignatureVerifier.hash( abi.encodePacked(_capsuleBytes, _cFragBytes), hashAlgorithm); require(!evaluatedCFrags[evaluationHash], "This CFrag has already been evaluated."); evaluatedCFrags[evaluationHash] = true; // 2. Verify correctness of re-encryption bool cFragIsCorrect = ReEncryptionValidator.validateCFrag(_capsuleBytes, _cFragBytes, _preComputedData); emit CFragEvaluated(evaluationHash, msg.sender, cFragIsCorrect); // 3. Verify associated public keys and signatures require(ReEncryptionValidator.checkSerializedCoordinates(_workerPublicKey), "Staker's public key is invalid"); require(ReEncryptionValidator.checkSerializedCoordinates(_requesterPublicKey), "Requester's public key is invalid"); UmbralDeserializer.PreComputedData memory precomp = _preComputedData.toPreComputedData(); // Verify worker's signature of CFrag require(SignatureVerifier.verify( _cFragBytes, abi.encodePacked(_cFragSignature, precomp.lostBytes[1]), _workerPublicKey, hashAlgorithm), "CFrag signature is invalid" ); // Verify worker's signature of taskSignature and that it corresponds to cfrag.proof.metadata UmbralDeserializer.CapsuleFrag memory cFrag = _cFragBytes.toCapsuleFrag(); require(SignatureVerifier.verify( _taskSignature, abi.encodePacked(cFrag.proof.metadata, precomp.lostBytes[2]), _workerPublicKey, hashAlgorithm), "Task signature is invalid" ); // Verify that _taskSignature is bob's signature of the task specification. // A task specification is: capsule + ursula pubkey + alice address + blockhash bytes32 stampXCoord; assembly { stampXCoord := mload(add(_workerPublicKey, 32)) } bytes memory stamp = abi.encodePacked(precomp.lostBytes[4], stampXCoord); require(SignatureVerifier.verify( abi.encodePacked(_capsuleBytes, stamp, _workerIdentityEvidence, precomp.alicesKeyAsAddress, bytes32(0)), abi.encodePacked(_taskSignature, precomp.lostBytes[3]), _requesterPublicKey, hashAlgorithm), "Specification signature is invalid" ); // 4. Extract worker address from stamp signature. address worker = SignatureVerifier.recover( SignatureVerifier.hashEIP191(stamp, byte(0x45)), // Currently, we use version E (0x45) of EIP191 signatures _workerIdentityEvidence); address staker = escrow.stakerFromWorker(worker); require(staker != address(0), "Worker must be related to a staker"); // 5. Check that staker can be slashed uint256 stakerValue = escrow.getAllTokens(staker); require(stakerValue > 0, "Staker has no tokens"); // 6. If CFrag was incorrect, slash staker if (!cFragIsCorrect) { (uint256 penalty, uint256 reward) = calculatePenaltyAndReward(staker, stakerValue); escrow.slashStaker(staker, penalty, msg.sender, reward); emit IncorrectCFragVerdict(evaluationHash, worker, staker); } } /** * @notice Calculate penalty to the staker and reward to the investigator * @param _staker Staker's address * @param _stakerValue Amount of tokens that belong to the staker */ function calculatePenaltyAndReward(address _staker, uint256 _stakerValue) internal returns (uint256 penalty, uint256 reward) { penalty = basePenalty.add(penaltyHistoryCoefficient.mul(penaltyHistory[_staker])); penalty = Math.min(penalty, _stakerValue.div(percentagePenaltyCoefficient)); reward = penalty.div(rewardCoefficient); // TODO add maximum condition or other overflow protection or other penalty condition (#305?) penaltyHistory[_staker] = penaltyHistory[_staker].add(1); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); require(delegateGet(_testTarget, this.evaluatedCFrags.selector, evaluationCFragHash) == (evaluatedCFrags[evaluationCFragHash] ? 1 : 0)); require(delegateGet(_testTarget, this.penaltyHistory.selector, bytes32(bytes20(RESERVED_ADDRESS))) == penaltyHistory[RESERVED_ADDRESS]); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // preparation for the verifyState method bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); evaluatedCFrags[evaluationCFragHash] = true; penaltyHistory[RESERVED_ADDRESS] = 123; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./UmbralDeserializer.sol"; import "./SignatureVerifier.sol"; /** * @notice Validates re-encryption correctness. */ library ReEncryptionValidator { using UmbralDeserializer for bytes; //------------------------------// // Umbral-specific constants // //------------------------------// // See parameter `u` of `UmbralParameters` class in pyUmbral // https://github.com/nucypher/pyUmbral/blob/master/umbral/params.py uint8 public constant UMBRAL_PARAMETER_U_SIGN = 0x02; uint256 public constant UMBRAL_PARAMETER_U_XCOORD = 0x03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f; uint256 public constant UMBRAL_PARAMETER_U_YCOORD = 0x7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936; //------------------------------// // SECP256K1-specific constants // //------------------------------// // Base field order uint256 constant FIELD_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // -2 mod FIELD_ORDER uint256 constant MINUS_2 = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2d; // (-1/2) mod FIELD_ORDER uint256 constant MINUS_ONE_HALF = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffe17; // /** * @notice Check correctness of re-encryption * @param _capsuleBytes Capsule * @param _cFragBytes Capsule frag * @param _precomputedBytes Additional precomputed data */ function validateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _precomputedBytes ) internal pure returns (bool) { UmbralDeserializer.Capsule memory _capsule = _capsuleBytes.toCapsule(); UmbralDeserializer.CapsuleFrag memory _cFrag = _cFragBytes.toCapsuleFrag(); UmbralDeserializer.PreComputedData memory _precomputed = _precomputedBytes.toPreComputedData(); // Extract Alice's address and check that it corresponds to the one provided address alicesAddress = SignatureVerifier.recover( _precomputed.hashedKFragValidityMessage, abi.encodePacked(_cFrag.proof.kFragSignature, _precomputed.lostBytes[0]) ); require(alicesAddress == _precomputed.alicesKeyAsAddress, "Bad KFrag signature"); // Compute proof's challenge scalar h, used in all ZKP verification equations uint256 h = computeProofChallengeScalar(_capsule, _cFrag); ////// // Verifying 1st equation: z*E == h*E_1 + E_2 ////// // Input validation: E require(checkCompressedPoint( _capsule.pointE.sign, _capsule.pointE.xCoord, _precomputed.pointEyCoord), "Precomputed Y coordinate of E doesn't correspond to compressed E point" ); // Input validation: z*E require(isOnCurve(_precomputed.pointEZxCoord, _precomputed.pointEZyCoord), "Point zE is not a valid EC point" ); require(ecmulVerify( _capsule.pointE.xCoord, // E_x _precomputed.pointEyCoord, // E_y _cFrag.proof.bnSig, // z _precomputed.pointEZxCoord, // zE_x _precomputed.pointEZyCoord), // zE_y "Precomputed z*E value is incorrect" ); // Input validation: E1 require(checkCompressedPoint( _cFrag.pointE1.sign, // E1_sign _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord), // E1_y "Precomputed Y coordinate of E1 doesn't correspond to compressed E1 point" ); // Input validation: h*E1 require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord), "Point h*E1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord, // E1_y h, _precomputed.pointE1HxCoord, // hE1_x _precomputed.pointE1HyCoord), // hE1_y "Precomputed h*E1 value is incorrect" ); // Input validation: E2 require(checkCompressedPoint( _cFrag.proof.pointE2.sign, // E2_sign _cFrag.proof.pointE2.xCoord, // E2_x _precomputed.pointE2yCoord), // E2_y "Precomputed Y coordinate of E2 doesn't correspond to compressed E2 point" ); bool equation_holds = eqAffineJacobian( [_precomputed.pointEZxCoord, _precomputed.pointEZyCoord], addAffineJacobian( [_cFrag.proof.pointE2.xCoord, _precomputed.pointE2yCoord], [_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 2nd equation: z*V == h*V_1 + V_2 ////// // Input validation: V require(checkCompressedPoint( _capsule.pointV.sign, _capsule.pointV.xCoord, _precomputed.pointVyCoord), "Precomputed Y coordinate of V doesn't correspond to compressed V point" ); // Input validation: z*V require(isOnCurve(_precomputed.pointVZxCoord, _precomputed.pointVZyCoord), "Point zV is not a valid EC point" ); require(ecmulVerify( _capsule.pointV.xCoord, // V_x _precomputed.pointVyCoord, // V_y _cFrag.proof.bnSig, // z _precomputed.pointVZxCoord, // zV_x _precomputed.pointVZyCoord), // zV_y "Precomputed z*V value is incorrect" ); // Input validation: V1 require(checkCompressedPoint( _cFrag.pointV1.sign, // V1_sign _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord), // V1_y "Precomputed Y coordinate of V1 doesn't correspond to compressed V1 point" ); // Input validation: h*V1 require(isOnCurve(_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord), "Point h*V1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord, // V1_y h, _precomputed.pointV1HxCoord, // h*V1_x _precomputed.pointV1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: V2 require(checkCompressedPoint( _cFrag.proof.pointV2.sign, // V2_sign _cFrag.proof.pointV2.xCoord, // V2_x _precomputed.pointV2yCoord), // V2_y "Precomputed Y coordinate of V2 doesn't correspond to compressed V2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointVZxCoord, _precomputed.pointVZyCoord], addAffineJacobian( [_cFrag.proof.pointV2.xCoord, _precomputed.pointV2yCoord], [_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 3rd equation: z*U == h*U_1 + U_2 ////// // We don't have to validate U since it's fixed and hard-coded // Input validation: z*U require(isOnCurve(_precomputed.pointUZxCoord, _precomputed.pointUZyCoord), "Point z*U is not a valid EC point" ); require(ecmulVerify( UMBRAL_PARAMETER_U_XCOORD, // U_x UMBRAL_PARAMETER_U_YCOORD, // U_y _cFrag.proof.bnSig, // z _precomputed.pointUZxCoord, // zU_x _precomputed.pointUZyCoord), // zU_y "Precomputed z*U value is incorrect" ); // Input validation: U1 (a.k.a. KFragCommitment) require(checkCompressedPoint( _cFrag.proof.pointKFragCommitment.sign, // U1_sign _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord), // U1_y "Precomputed Y coordinate of U1 doesn't correspond to compressed U1 point" ); // Input validation: h*U1 require(isOnCurve(_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord), "Point h*U1 is not a valid EC point" ); require(ecmulVerify( _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord, // U1_y h, _precomputed.pointU1HxCoord, // h*V1_x _precomputed.pointU1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: U2 (a.k.a. KFragPok ("proof of knowledge")) require(checkCompressedPoint( _cFrag.proof.pointKFragPok.sign, // U2_sign _cFrag.proof.pointKFragPok.xCoord, // U2_x _precomputed.pointU2yCoord), // U2_y "Precomputed Y coordinate of U2 doesn't correspond to compressed U2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointUZxCoord, _precomputed.pointUZyCoord], addAffineJacobian( [_cFrag.proof.pointKFragPok.xCoord, _precomputed.pointU2yCoord], [_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord] ) ); return equation_holds; } function computeProofChallengeScalar( UmbralDeserializer.Capsule memory _capsule, UmbralDeserializer.CapsuleFrag memory _cFrag ) internal pure returns (uint256) { // Compute h = hash_to_bignum(e, e1, e2, v, v1, v2, u, u1, u2, metadata) bytes memory hashInput = abi.encodePacked( // Point E _capsule.pointE.sign, _capsule.pointE.xCoord, // Point E1 _cFrag.pointE1.sign, _cFrag.pointE1.xCoord, // Point E2 _cFrag.proof.pointE2.sign, _cFrag.proof.pointE2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point V _capsule.pointV.sign, _capsule.pointV.xCoord, // Point V1 _cFrag.pointV1.sign, _cFrag.pointV1.xCoord, // Point V2 _cFrag.proof.pointV2.sign, _cFrag.proof.pointV2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point U bytes1(UMBRAL_PARAMETER_U_SIGN), bytes32(UMBRAL_PARAMETER_U_XCOORD), // Point U1 _cFrag.proof.pointKFragCommitment.sign, _cFrag.proof.pointKFragCommitment.xCoord, // Point U2 _cFrag.proof.pointKFragPok.sign, _cFrag.proof.pointKFragPok.xCoord, // Re-encryption metadata _cFrag.proof.metadata ); uint256 h = extendedKeccakToBN(hashInput); return h; } function extendedKeccakToBN (bytes memory _data) internal pure returns (uint256) { bytes32 upper; bytes32 lower; // Umbral prepends to the data a customization string of 64-bytes. // In the case of hash_to_curvebn is 'hash_to_curvebn', padded with zeroes. bytes memory input = abi.encodePacked(bytes32("hash_to_curvebn"), bytes32(0x00), _data); (upper, lower) = (keccak256(abi.encodePacked(uint8(0x00), input)), keccak256(abi.encodePacked(uint8(0x01), input))); // Let n be the order of secp256k1's group (n = 2^256 - 0x1000003D1) // n_minus_1 = n - 1 // delta = 2^256 mod n_minus_1 uint256 delta = 0x14551231950b75fc4402da1732fc9bec0; uint256 n_minus_1 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140; uint256 upper_half = mulmod(uint256(upper), delta, n_minus_1); return 1 + addmod(upper_half, uint256(lower), n_minus_1); } /// @notice Tests if a compressed point is valid, wrt to its corresponding Y coordinate /// @param _pointSign The sign byte from the compressed notation: 0x02 if the Y coord is even; 0x03 otherwise /// @param _pointX The X coordinate of an EC point in affine representation /// @param _pointY The Y coordinate of an EC point in affine representation /// @return true iff _pointSign and _pointX are the compressed representation of (_pointX, _pointY) function checkCompressedPoint( uint8 _pointSign, uint256 _pointX, uint256 _pointY ) internal pure returns(bool) { bool correct_sign = _pointY % 2 == _pointSign - 2; return correct_sign && isOnCurve(_pointX, _pointY); } /// @notice Tests if the given serialized coordinates represent a valid EC point /// @param _coords The concatenation of serialized X and Y coordinates /// @return true iff coordinates X and Y are a valid point function checkSerializedCoordinates(bytes memory _coords) internal pure returns(bool) { require(_coords.length == 64, "Serialized coordinates should be 64 B"); uint256 coordX; uint256 coordY; assembly { coordX := mload(add(_coords, 32)) coordY := mload(add(_coords, 64)) } return isOnCurve(coordX, coordY); } /// @notice Tests if a point is on the secp256k1 curve /// @param Px The X coordinate of an EC point in affine representation /// @param Py The Y coordinate of an EC point in affine representation /// @return true if (Px, Py) is a valid secp256k1 point; false otherwise function isOnCurve(uint256 Px, uint256 Py) internal pure returns (bool) { uint256 p = FIELD_ORDER; if (Px >= p || Py >= p){ return false; } uint256 y2 = mulmod(Py, Py, p); uint256 x3_plus_7 = addmod(mulmod(mulmod(Px, Px, p), Px, p), 7, p); return y2 == x3_plus_7; } // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/4 function ecmulVerify( uint256 x1, uint256 y1, uint256 scalar, uint256 qx, uint256 qy ) internal pure returns(bool) { uint256 curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; address signer = ecrecover(0, uint8(27 + (y1 % 2)), bytes32(x1), bytes32(mulmod(scalar, x1, curve_order))); address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return xyAddress == signer; } /// @notice Equality test of two points, in affine and Jacobian coordinates respectively /// @param P An EC point in affine coordinates /// @param Q An EC point in Jacobian coordinates /// @return true if P and Q represent the same point in affine coordinates; false otherwise function eqAffineJacobian( uint256[2] memory P, uint256[3] memory Q ) internal pure returns(bool){ uint256 Qz = Q[2]; if(Qz == 0){ return false; // Q is zero but P isn't. } uint256 p = FIELD_ORDER; uint256 Q_z_squared = mulmod(Qz, Qz, p); return mulmod(P[0], Q_z_squared, p) == Q[0] && mulmod(P[1], mulmod(Q_z_squared, Qz, p), p) == Q[1]; } /// @notice Adds two points in affine coordinates, with the result in Jacobian /// @dev Based on the addition formulas from http://www.hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2001-b.op3 /// @param P An EC point in affine coordinates /// @param Q An EC point in affine coordinates /// @return R An EC point in Jacobian coordinates with the sum, represented by an array of 3 uint256 function addAffineJacobian( uint[2] memory P, uint[2] memory Q ) internal pure returns (uint[3] memory R) { uint256 p = FIELD_ORDER; uint256 a = P[0]; uint256 c = P[1]; uint256 t0 = Q[0]; uint256 t1 = Q[1]; if ((a == t0) && (c == t1)){ return doubleJacobian([a, c, 1]); } uint256 d = addmod(t1, p-c, p); // d = t1 - c uint256 b = addmod(t0, p-a, p); // b = t0 - a uint256 e = mulmod(b, b, p); // e = b^2 uint256 f = mulmod(e, b, p); // f = b^3 uint256 g = mulmod(a, e, p); R[0] = addmod(mulmod(d, d, p), p-addmod(mulmod(2, g, p), f, p), p); R[1] = addmod(mulmod(d, addmod(g, p-R[0], p), p), p-mulmod(c, f, p), p); R[2] = b; } /// @notice Point doubling in Jacobian coordinates /// @param P An EC point in Jacobian coordinates. /// @return Q An EC point in Jacobian coordinates function doubleJacobian(uint[3] memory P) internal pure returns (uint[3] memory Q) { uint256 z = P[2]; if (z == 0) return Q; uint256 p = FIELD_ORDER; uint256 x = P[0]; uint256 _2y = mulmod(2, P[1], p); uint256 _4yy = mulmod(_2y, _2y, p); uint256 s = mulmod(_4yy, x, p); uint256 m = mulmod(3, mulmod(x, x, p), p); uint256 t = addmod(mulmod(m, m, p), mulmod(MINUS_2, s, p),p); Q[0] = t; Q[1] = addmod(mulmod(m, addmod(s, p - t, p), p), mulmod(MINUS_ONE_HALF, mulmod(_4yy, _4yy, p), p), p); Q[2] = mulmod(_2y, z, p); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Deserialization library for Umbral objects */ library UmbralDeserializer { struct Point { uint8 sign; uint256 xCoord; } struct Capsule { Point pointE; Point pointV; uint256 bnSig; } struct CorrectnessProof { Point pointE2; Point pointV2; Point pointKFragCommitment; Point pointKFragPok; uint256 bnSig; bytes kFragSignature; // 64 bytes bytes metadata; // any length } struct CapsuleFrag { Point pointE1; Point pointV1; bytes32 kFragId; Point pointPrecursor; CorrectnessProof proof; } struct PreComputedData { uint256 pointEyCoord; uint256 pointEZxCoord; uint256 pointEZyCoord; uint256 pointE1yCoord; uint256 pointE1HxCoord; uint256 pointE1HyCoord; uint256 pointE2yCoord; uint256 pointVyCoord; uint256 pointVZxCoord; uint256 pointVZyCoord; uint256 pointV1yCoord; uint256 pointV1HxCoord; uint256 pointV1HyCoord; uint256 pointV2yCoord; uint256 pointUZxCoord; uint256 pointUZyCoord; uint256 pointU1yCoord; uint256 pointU1HxCoord; uint256 pointU1HyCoord; uint256 pointU2yCoord; bytes32 hashedKFragValidityMessage; address alicesKeyAsAddress; bytes5 lostBytes; } uint256 constant BIGNUM_SIZE = 32; uint256 constant POINT_SIZE = 33; uint256 constant SIGNATURE_SIZE = 64; uint256 constant CAPSULE_SIZE = 2 * POINT_SIZE + BIGNUM_SIZE; uint256 constant CORRECTNESS_PROOF_SIZE = 4 * POINT_SIZE + BIGNUM_SIZE + SIGNATURE_SIZE; uint256 constant CAPSULE_FRAG_SIZE = 3 * POINT_SIZE + BIGNUM_SIZE; uint256 constant FULL_CAPSULE_FRAG_SIZE = CAPSULE_FRAG_SIZE + CORRECTNESS_PROOF_SIZE; uint256 constant PRECOMPUTED_DATA_SIZE = (20 * BIGNUM_SIZE) + 32 + 20 + 5; /** * @notice Deserialize to capsule (not activated) */ function toCapsule(bytes memory _capsuleBytes) internal pure returns (Capsule memory capsule) { require(_capsuleBytes.length == CAPSULE_SIZE); uint256 pointer = getPointer(_capsuleBytes); pointer = copyPoint(pointer, capsule.pointE); pointer = copyPoint(pointer, capsule.pointV); capsule.bnSig = uint256(getBytes32(pointer)); } /** * @notice Deserialize to correctness proof * @param _pointer Proof bytes memory pointer * @param _proofBytesLength Proof bytes length */ function toCorrectnessProof(uint256 _pointer, uint256 _proofBytesLength) internal pure returns (CorrectnessProof memory proof) { require(_proofBytesLength >= CORRECTNESS_PROOF_SIZE); _pointer = copyPoint(_pointer, proof.pointE2); _pointer = copyPoint(_pointer, proof.pointV2); _pointer = copyPoint(_pointer, proof.pointKFragCommitment); _pointer = copyPoint(_pointer, proof.pointKFragPok); proof.bnSig = uint256(getBytes32(_pointer)); _pointer += BIGNUM_SIZE; proof.kFragSignature = new bytes(SIGNATURE_SIZE); // TODO optimize, just two mload->mstore (#1500) _pointer = copyBytes(_pointer, proof.kFragSignature, SIGNATURE_SIZE); if (_proofBytesLength > CORRECTNESS_PROOF_SIZE) { proof.metadata = new bytes(_proofBytesLength - CORRECTNESS_PROOF_SIZE); copyBytes(_pointer, proof.metadata, proof.metadata.length); } } /** * @notice Deserialize to correctness proof */ function toCorrectnessProof(bytes memory _proofBytes) internal pure returns (CorrectnessProof memory proof) { uint256 pointer = getPointer(_proofBytes); return toCorrectnessProof(pointer, _proofBytes.length); } /** * @notice Deserialize to CapsuleFrag */ function toCapsuleFrag(bytes memory _cFragBytes) internal pure returns (CapsuleFrag memory cFrag) { uint256 cFragBytesLength = _cFragBytes.length; require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE); uint256 pointer = getPointer(_cFragBytes); pointer = copyPoint(pointer, cFrag.pointE1); pointer = copyPoint(pointer, cFrag.pointV1); cFrag.kFragId = getBytes32(pointer); pointer += BIGNUM_SIZE; pointer = copyPoint(pointer, cFrag.pointPrecursor); cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE); } /** * @notice Deserialize to precomputed data */ function toPreComputedData(bytes memory _preComputedData) internal pure returns (PreComputedData memory data) { require(_preComputedData.length == PRECOMPUTED_DATA_SIZE); uint256 initial_pointer = getPointer(_preComputedData); uint256 pointer = initial_pointer; data.pointEyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.hashedKFragValidityMessage = getBytes32(pointer); pointer += 32; data.alicesKeyAsAddress = address(bytes20(getBytes32(pointer))); pointer += 20; // Lost bytes: a bytes5 variable holding the following byte values: // 0: kfrag signature recovery value v // 1: cfrag signature recovery value v // 2: metadata signature recovery value v // 3: specification signature recovery value v // 4: ursula pubkey sign byte data.lostBytes = bytes5(getBytes32(pointer)); pointer += 5; require(pointer == initial_pointer + PRECOMPUTED_DATA_SIZE); } // TODO extract to external library if needed (#1500) /** * @notice Get the memory pointer for start of array */ function getPointer(bytes memory _bytes) internal pure returns (uint256 pointer) { assembly { pointer := add(_bytes, 32) // skip array length } } /** * @notice Copy point data from memory in the pointer position */ function copyPoint(uint256 _pointer, Point memory _point) internal pure returns (uint256 resultPointer) { // TODO optimize, copy to point memory directly (#1500) uint8 temp; uint256 xCoord; assembly { temp := byte(0, mload(_pointer)) xCoord := mload(add(_pointer, 1)) } _point.sign = temp; _point.xCoord = xCoord; resultPointer = _pointer + POINT_SIZE; } /** * @notice Read 1 byte from memory in the pointer position */ function getByte(uint256 _pointer) internal pure returns (byte result) { bytes32 word; assembly { word := mload(_pointer) } result = word[0]; return result; } /** * @notice Read 32 bytes from memory in the pointer position */ function getBytes32(uint256 _pointer) internal pure returns (bytes32 result) { assembly { result := mload(_pointer) } } /** * @notice Copy bytes from the source pointer to the target array * @dev Assumes that enough memory has been allocated to store in target. * Also assumes that '_target' was the last thing that was allocated * @param _bytesPointer Source memory pointer * @param _target Target array * @param _bytesLength Number of bytes to copy */ function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength) internal pure returns (uint256 resultPointer) { // Exploiting the fact that '_target' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. assembly { // evm operations on words let words := div(add(_bytesLength, 31), 32) let source := _bytesPointer let destination := add(_target, 32) for { let i := 0 } // start at arr + 32 -> first byte corresponds to length lt(i, words) { i := add(i, 1) } { let offset := mul(i, 32) mstore(add(destination, offset), mload(add(source, offset))) } mstore(add(_target, add(32, mload(_target))), 0) } resultPointer = _bytesPointer + _bytesLength; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Library to recover address and verify signatures * @dev Simple wrapper for `ecrecover` */ library SignatureVerifier { enum HashAlgorithm {KECCAK256, SHA256, RIPEMD160} // Header for Version E as defined by EIP191. First byte ('E') is also the version bytes25 constant EIP191_VERSION_E_HEADER = "Ethereum Signed Message:\n"; /** * @notice Recover signer address from hash and signature * @param _hash 32 bytes message hash * @param _signature Signature of hash - 32 bytes r + 32 bytes s + 1 byte v (could be 0, 1, 27, 28) */ function recover(bytes32 _hash, bytes memory _signature) internal pure returns (address) { require(_signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); return ecrecover(_hash, v, r, s); } /** * @notice Transform public key to address * @param _publicKey secp256k1 public key */ function toAddress(bytes memory _publicKey) internal pure returns (address) { return address(uint160(uint256(keccak256(_publicKey)))); } /** * @notice Hash using one of pre built hashing algorithm * @param _message Signed message * @param _algorithm Hashing algorithm */ function hash(bytes memory _message, HashAlgorithm _algorithm) internal pure returns (bytes32 result) { if (_algorithm == HashAlgorithm.KECCAK256) { result = keccak256(_message); } else if (_algorithm == HashAlgorithm.SHA256) { result = sha256(_message); } else { result = ripemd160(_message); } } /** * @notice Verify ECDSA signature * @dev Uses one of pre built hashing algorithm * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _algorithm Hashing algorithm */ function verify( bytes memory _message, bytes memory _signature, bytes memory _publicKey, HashAlgorithm _algorithm ) internal pure returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hash(_message, _algorithm), _signature); } /** * @notice Hash message according to EIP191 signature specification * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Message to sign * @param _version EIP191 version to use */ function hashEIP191( bytes memory _message, byte _version ) internal view returns (bytes32 result) { if(_version == byte(0x00)){ // Version 0: Data with intended validator address validator = address(this); return keccak256(abi.encodePacked(byte(0x19), byte(0x00), validator, _message)); } else if (_version == byte(0x45)){ // Version E: personal_sign messages uint256 length = _message.length; require(length > 0, "Empty message not allowed for version E"); // Compute text-encoded length of message uint256 digits = 0; while (length != 0) { digits++; length /= 10; } bytes memory lengthAsText = new bytes(digits); length = _message.length; uint256 index = digits - 1; while (length != 0) { lengthAsText[index--] = byte(uint8(48 + length % 10)); length /= 10; } return keccak256(abi.encodePacked(byte(0x19), EIP191_VERSION_E_HEADER, lengthAsText, _message)); } else { revert("Unsupported EIP191 version"); } } /** * @notice Verify EIP191 signature * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _version EIP191 version to use */ function verifyEIP191( bytes memory _message, bytes memory _signature, bytes memory _publicKey, byte _version ) internal view returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hashEIP191(_message, _version), _signature); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../aragon/interfaces/IERC900History.sol"; import "./Issuer.sol"; import "./lib/Bits.sol"; import "./lib/Snapshot.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @notice PolicyManager interface */ interface PolicyManagerInterface { function secondsPerPeriod() external view returns (uint32); function register(address _node, uint16 _period) external; function migrate(address _node) external; function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external; } /** * @notice Adjudicator interface */ interface AdjudicatorInterface { function rewardCoefficient() external view returns (uint32); } /** * @notice WorkLock interface */ interface WorkLockInterface { function token() external view returns (NuCypherToken); } /** * @title StakingEscrowStub * @notice Stub is used to deploy main StakingEscrow after all other contract and make some variables immutable * @dev |v1.0.0| */ contract StakingEscrowStub is Upgradeable { using AdditionalMath for uint32; NuCypherToken public immutable token; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; uint16 public immutable minLockedPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; /** * @notice Predefines some variables for use when deploying other contracts * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens ) { require(_token.totalSupply() > 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); // we have to use real values even though this is a stub require(address(delegateGet(_testTarget, this.token.selector)) == address(token)); // TODO uncomment after merging this PR #2579 // require(uint32(delegateGet(_testTarget, this.genesisSecondsPerPeriod.selector)) == genesisSecondsPerPeriod); require(uint32(delegateGet(_testTarget, this.secondsPerPeriod.selector)) == secondsPerPeriod); require(uint16(delegateGet(_testTarget, this.minLockedPeriods.selector)) == minLockedPeriods); require(delegateGet(_testTarget, this.minAllowableLockedTokens.selector) == minAllowableLockedTokens); require(delegateGet(_testTarget, this.maxAllowableLockedTokens.selector) == maxAllowableLockedTokens); } } /** * @title StakingEscrow * @notice Contract holds and locks stakers tokens. * Each staker that locks their tokens will receive some compensation * @dev |v5.7.1| */ contract StakingEscrow is Issuer, IERC900History { using AdditionalMath for uint256; using AdditionalMath for uint16; using Bits for uint256; using SafeMath for uint256; using Snapshot for uint128[]; using SafeERC20 for NuCypherToken; /** * @notice Signals that tokens were deposited * @param staker Staker address * @param value Amount deposited (in NuNits) * @param periods Number of periods tokens will be locked */ event Deposited(address indexed staker, uint256 value, uint16 periods); /** * @notice Signals that tokens were stake locked * @param staker Staker address * @param value Amount locked (in NuNits) * @param firstPeriod Starting lock period * @param periods Number of periods tokens will be locked */ event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods); /** * @notice Signals that a sub-stake was divided * @param staker Staker address * @param oldValue Old sub-stake value (in NuNits) * @param lastPeriod Final locked period of old sub-stake * @param newValue New sub-stake value (in NuNits) * @param periods Number of periods to extend sub-stake */ event Divided( address indexed staker, uint256 oldValue, uint16 lastPeriod, uint256 newValue, uint16 periods ); /** * @notice Signals that two sub-stakes were merged * @param staker Staker address * @param value1 Value of first sub-stake (in NuNits) * @param value2 Value of second sub-stake (in NuNits) * @param lastPeriod Final locked period of merged sub-stake */ event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod); /** * @notice Signals that a sub-stake was prolonged * @param staker Staker address * @param value Value of sub-stake * @param lastPeriod Final locked period of old sub-stake * @param periods Number of periods sub-stake was extended */ event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods); /** * @notice Signals that tokens were withdrawn to the staker * @param staker Staker address * @param value Amount withdraws (in NuNits) */ event Withdrawn(address indexed staker, uint256 value); /** * @notice Signals that the worker associated with the staker made a commitment to next period * @param staker Staker address * @param period Period committed to * @param value Amount of tokens staked for the committed period */ event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that tokens were minted for previous periods * @param staker Staker address * @param period Previous period tokens minted for * @param value Amount minted (in NuNits) */ event Minted(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that the staker was slashed * @param staker Staker address * @param penalty Slashing penalty * @param investigator Investigator address * @param reward Value of reward provided to investigator (in NuNits) */ event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward); /** * @notice Signals that the restake parameter was activated/deactivated * @param staker Staker address * @param reStake Updated parameter value */ event ReStakeSet(address indexed staker, bool reStake); /** * @notice Signals that a worker was bonded to the staker * @param staker Staker address * @param worker Worker address * @param startPeriod Period bonding occurred */ event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod); /** * @notice Signals that the winddown parameter was activated/deactivated * @param staker Staker address * @param windDown Updated parameter value */ event WindDownSet(address indexed staker, bool windDown); /** * @notice Signals that the snapshot parameter was activated/deactivated * @param staker Staker address * @param snapshotsEnabled Updated parameter value */ event SnapshotSet(address indexed staker, bool snapshotsEnabled); /** * @notice Signals that the staker migrated their stake to the new period length * @param staker Staker address * @param period Period when migration happened */ event Migrated(address indexed staker, uint16 indexed period); /// internal event event WorkMeasurementSet(address indexed staker, bool measureWork); struct SubStakeInfo { uint16 firstPeriod; uint16 lastPeriod; uint16 unlockingDuration; uint128 lockedValue; } struct Downtime { uint16 startPeriod; uint16 endPeriod; } struct StakerInfo { uint256 value; /* * Stores periods that are committed but not yet rewarded. * In order to optimize storage, only two values are used instead of an array. * commitToNextPeriod() method invokes mint() method so there can only be two committed * periods that are not yet rewarded: the current and the next periods. */ uint16 currentCommittedPeriod; uint16 nextCommittedPeriod; uint16 lastCommittedPeriod; uint16 stub1; // former slot for lockReStakeUntilPeriod uint256 completedWork; uint16 workerStartPeriod; // period when worker was bonded address worker; uint256 flags; // uint256 to acquire whole slot and minimize operations on it uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; Downtime[] pastDowntime; SubStakeInfo[] subStakes; uint128[] history; } // used only for upgrading uint16 internal constant RESERVED_PERIOD = 0; uint16 internal constant MAX_CHECKED_VALUES = 5; // to prevent high gas consumption in loops for slashing uint16 public constant MAX_SUB_STAKES = 30; uint16 internal constant MAX_UINT16 = 65535; // indices for flags uint8 internal constant RE_STAKE_DISABLED_INDEX = 0; uint8 internal constant WIND_DOWN_INDEX = 1; uint8 internal constant MEASURE_WORK_INDEX = 2; uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3; uint8 internal constant MIGRATED_INDEX = 4; uint16 public immutable minLockedPeriods; uint16 public immutable minWorkerPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; PolicyManagerInterface public immutable policyManager; AdjudicatorInterface public immutable adjudicator; WorkLockInterface public immutable workLock; mapping (address => StakerInfo) public stakerInfo; address[] public stakers; mapping (address => address) public stakerFromWorker; mapping (uint16 => uint256) stub4; // former slot for lockedPerPeriod uint128[] public balanceHistory; address stub1; // former slot for PolicyManager address stub2; // former slot for Adjudicator address stub3; // former slot for WorkLock mapping (uint16 => uint256) _lockedPerPeriod; // only to make verifyState from previous version work, temporary // TODO remove after upgrade #2579 function lockedPerPeriod(uint16 _period) public view returns (uint256) { return _period != RESERVED_PERIOD ? _lockedPerPeriod[_period] : 111; } /** * @notice Constructor sets address of token contract and coefficients for minting * @param _token Token contract * @param _policyManager Policy Manager contract * @param _adjudicator Adjudicator contract * @param _workLock WorkLock contract. Zero address if there is no WorkLock * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked * @param _minWorkerPeriods Min amount of periods while a worker can't be changed */ constructor( NuCypherToken _token, PolicyManagerInterface _policyManager, AdjudicatorInterface _adjudicator, WorkLockInterface _workLock, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens, uint16 _minWorkerPeriods ) Issuer( _token, _genesisHoursPerPeriod, _hoursPerPeriod, _issuanceDecayCoefficient, _lockDurationCoefficient1, _lockDurationCoefficient2, _maximumRewardedPeriods, _firstPhaseTotalSupply, _firstPhaseMaxIssuance ) { // constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; minWorkerPeriods = _minWorkerPeriods; require((_policyManager.secondsPerPeriod() == _hoursPerPeriod * (1 hours) || _policyManager.secondsPerPeriod() == _genesisHoursPerPeriod * (1 hours)) && _adjudicator.rewardCoefficient() != 0 && (address(_workLock) == address(0) || _workLock.token() == _token)); policyManager = _policyManager; adjudicator = _adjudicator; workLock = _workLock; } /** * @dev Checks the existence of a staker in the contract */ modifier onlyStaker() { StakerInfo storage info = stakerInfo[msg.sender]; require((info.value > 0 || info.nextCommittedPeriod != 0) && info.flags.bitSet(MIGRATED_INDEX)); _; } //------------------------Main getters------------------------ /** * @notice Get all tokens belonging to the staker */ function getAllTokens(address _staker) external view returns (uint256) { return stakerInfo[_staker].value; } /** * @notice Get all flags for the staker */ function getFlags(address _staker) external view returns ( bool windDown, bool reStake, bool measureWork, bool snapshots, bool migrated ) { StakerInfo storage info = stakerInfo[_staker]; windDown = info.flags.bitSet(WIND_DOWN_INDEX); reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); measureWork = info.flags.bitSet(MEASURE_WORK_INDEX); snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX); migrated = info.flags.bitSet(MIGRATED_INDEX); } /** * @notice Get the start period. Use in the calculation of the last period of the sub stake * @param _info Staker structure * @param _currentPeriod Current period */ function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod) internal view returns (uint16) { // if the next period (after current) is committed if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) { return _currentPeriod + 1; } return _currentPeriod; } /** * @notice Get the last period of the sub stake * @param _subStake Sub stake structure * @param _startPeriod Pre-calculated start period */ function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod) internal view returns (uint16) { if (_subStake.lastPeriod != 0) { return _subStake.lastPeriod; } uint32 lastPeriod = uint32(_startPeriod) + _subStake.unlockingDuration; if (lastPeriod > uint32(MAX_UINT16)) { return MAX_UINT16; } return uint16(lastPeriod); } /** * @notice Get the last period of the sub stake * @param _staker Staker * @param _index Stake index */ function getLastPeriodOfSubStake(address _staker, uint256 _index) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; SubStakeInfo storage subStake = info.subStakes[_index]; uint16 startPeriod = getStartPeriod(info, getCurrentPeriod()); return getLastPeriodOfSubStake(subStake, startPeriod); } /** * @notice Get the value of locked tokens for a staker in a specified period * @dev Information may be incorrect for rewarded or not committed surpassed period * @param _info Staker structure * @param _currentPeriod Current period * @param _period Next period */ function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period) internal view returns (uint256 lockedValue) { lockedValue = 0; uint16 startPeriod = getStartPeriod(_info, _currentPeriod); for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.firstPeriod <= _period && getLastPeriodOfSubStake(subStake, startPeriod) >= _period) { lockedValue += subStake.lockedValue; } } } /** * @notice Get the value of locked tokens for a staker in a future period * @dev This function is used by PreallocationEscrow so its signature can't be updated. * @param _staker Staker * @param _offsetPeriods Amount of periods that will be added to the current period */ function getLockedTokens(address _staker, uint16 _offsetPeriods) external view returns (uint256 lockedValue) { StakerInfo storage info = stakerInfo[_staker]; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); return getLockedTokens(info, currentPeriod, nextPeriod); } /** * @notice Get the last committed staker's period * @param _staker Staker */ function getLastCommittedPeriod(address _staker) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod; } /** * @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _offsetPeriods) period * as well as stakers and their locked tokens * @param _offsetPeriods Amount of periods for locked tokens calculation * @param _startIndex Start index for looking in stakers array * @param _maxStakers Max stakers for looking, if set 0 then all will be used * @return allLockedTokens Sum of locked tokens for active stakers * @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256 * @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly! */ function getActiveStakers(uint16 _offsetPeriods, uint256 _startIndex, uint256 _maxStakers) external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers) { require(_offsetPeriods > 0); uint256 endIndex = stakers.length; require(_startIndex < endIndex); if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) { endIndex = _startIndex + _maxStakers; } activeStakers = new uint256[2][](endIndex - _startIndex); allLockedTokens = 0; uint256 resultIndex = 0; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); for (uint256 i = _startIndex; i < endIndex; i++) { address staker = stakers[i]; StakerInfo storage info = stakerInfo[staker]; if (info.currentCommittedPeriod != currentPeriod && info.nextCommittedPeriod != currentPeriod) { continue; } uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); if (lockedTokens != 0) { activeStakers[resultIndex][0] = uint256(staker); activeStakers[resultIndex++][1] = lockedTokens; allLockedTokens += lockedTokens; } } assembly { mstore(activeStakers, resultIndex) } } /** * @notice Get worker using staker's address */ function getWorkerFromStaker(address _staker) external view returns (address) { return stakerInfo[_staker].worker; } /** * @notice Get work that completed by the staker */ function getCompletedWork(address _staker) external view returns (uint256) { return stakerInfo[_staker].completedWork; } /** * @notice Find index of downtime structure that includes specified period * @dev If specified period is outside all downtime periods, the length of the array will be returned * @param _staker Staker * @param _period Specified period number */ function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) { StakerInfo storage info = stakerInfo[_staker]; for (index = 0; index < info.pastDowntime.length; index++) { if (_period <= info.pastDowntime[index].endPeriod) { return index; } } } //------------------------Main methods------------------------ /** * @notice Start or stop measuring the work of a staker * @param _staker Staker * @param _measureWork Value for `measureWork` parameter * @return Work that was previously done */ function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) { return info.completedWork; } info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX); emit WorkMeasurementSet(_staker, _measureWork); return info.completedWork; } /** * @notice Bond worker * @param _worker Worker address. Must be a real address, not a contract */ function bondWorker(address _worker) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Specified worker is already bonded with this staker require(_worker != info.worker); uint16 currentPeriod = getCurrentPeriod(); if (info.worker != address(0)) { // If this staker had a worker ... // Check that enough time has passed to change it require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods)); // Remove the old relation "worker->staker" stakerFromWorker[info.worker] = address(0); } if (_worker != address(0)) { // Specified worker is already in use require(stakerFromWorker[_worker] == address(0)); // Specified worker is a staker require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender); // Set new worker->staker relation stakerFromWorker[_worker] = msg.sender; } // Bond new worker (or unbond if _worker == address(0)) info.worker = _worker; info.workerStartPeriod = currentPeriod; emit WorkerBonded(msg.sender, _worker, currentPeriod); } /** * @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake * @param _reStake Value for parameter */ function setReStake(bool _reStake) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) { return; } info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens from WorkLock contract * @param _staker Staker address * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function depositFromWorkLock( address _staker, uint256 _value, uint16 _unlockingDuration ) external { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (!info.flags.bitSet(WIND_DOWN_INDEX) && info.subStakes.length == 0) { info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(_staker, true); } // WorkLock still uses the genesis period length (24h) _unlockingDuration = recalculatePeriod(_unlockingDuration); deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Set `windDown` parameter. * If true then stake's duration will be decreasing in each period with `commitToNextPeriod()` * @param _windDown Value for parameter */ function setWindDown(bool _windDown) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) { return; } info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(msg.sender, _windDown); // duration adjustment if next period is committed uint16 nextPeriod = getCurrentPeriod() + 1; if (info.nextCommittedPeriod != nextPeriod) { return; } // adjust sub-stakes duration for the new value of winding down parameter for (uint256 index = 0; index < info.subStakes.length; index++) { SubStakeInfo storage subStake = info.subStakes[index]; // sub-stake does not have fixed last period when winding down is disabled if (!_windDown && subStake.lastPeriod == nextPeriod) { subStake.lastPeriod = 0; subStake.unlockingDuration = 1; continue; } // this sub-stake is no longer affected by winding down parameter if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration = _windDown ? subStake.unlockingDuration - 1 : subStake.unlockingDuration + 1; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = nextPeriod; } } } /** * @notice Activate/deactivate taking snapshots of balances * @param _enableSnapshots True to activate snapshots, False to deactivate */ function setSnapshots(bool _enableSnapshots) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) { return; } uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); if(_enableSnapshots){ info.history.addSnapshot(info.value); balanceHistory.addSnapshot(lastGlobalBalance + info.value); } else { info.history.addSnapshot(0); balanceHistory.addSnapshot(lastGlobalBalance - info.value); } info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Adds a new snapshot to both the staker and global balance histories, * assuming the staker's balance was already changed * @param _info Reference to affected staker's struct * @param _addition Variance in balance. It can be positive or negative. */ function addSnapshot(StakerInfo storage _info, int256 _addition) internal { if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){ _info.history.addSnapshot(_info.value); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition)); } } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Deposit all tokens that were approved to transfer * @param _from Staker * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of periods during which tokens will be unlocked when wind down is enabled */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload)); } /** * @notice Deposit tokens and create new sub-stake. Use this method to become a staker * @param _staker Staker * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, uint256 _value, uint16 _unlockingDuration) external { deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Deposit tokens and increase lock amount of an existing sub-stake * @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); deposit(msg.sender, msg.sender, _index, _value, 0); } /** * @notice Deposit tokens * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _payer Owner of tokens * @param _index Index of the sub stake * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { require(_value != 0); StakerInfo storage info = stakerInfo[_staker]; // A staker can't be a worker for another staker require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker); // initial stake of the staker if (info.subStakes.length == 0 && info.lastCommittedPeriod == 0) { stakers.push(_staker); policyManager.register(_staker, getCurrentPeriod() - 1); info.flags = info.flags.toggleBit(MIGRATED_INDEX); } require(info.flags.bitSet(MIGRATED_INDEX)); token.safeTransferFrom(_payer, address(this), _value); info.value += _value; lock(_staker, _index, _value, _unlockingDuration); addSnapshot(info, int256(_value)); if (_index >= MAX_SUB_STAKES) { emit Deposited(_staker, _value, _unlockingDuration); } else { uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index); emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod()); } } /** * @notice Lock some tokens as a new sub-stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate(uint256 _value, uint16 _unlockingDuration) external onlyStaker { lock(msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); lock(msg.sender, _index, _value, 0); } /** * @notice Lock some tokens as a stake * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lock(address _staker, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { if (_index < MAX_SUB_STAKES) { require(_value > 0); } else { require(_value >= minAllowableLockedTokens && _unlockingDuration >= minLockedPeriods); } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[_staker]; uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); uint256 requestedLockedTokens = _value.add(lockedTokens); require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens); // next period is committed if (info.nextCommittedPeriod == nextPeriod) { _lockedPerPeriod[nextPeriod] += _value; emit CommitmentMade(_staker, nextPeriod, _value); } // if index was provided then increase existing sub-stake if (_index < MAX_SUB_STAKES) { lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value); // otherwise create new } else { lockAndCreate(info, nextPeriod, _staker, _value, _unlockingDuration); } } /** * @notice Lock some tokens as a new sub-stake * @param _info Staker structure * @param _nextPeriod Next period * @param _staker Staker * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate( StakerInfo storage _info, uint16 _nextPeriod, address _staker, uint256 _value, uint16 _unlockingDuration ) internal { uint16 duration = _unlockingDuration; // if winding down is enabled and next period is committed // then sub-stakes duration were decreased if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) { duration -= 1; } saveSubStake(_info, _nextPeriod, 0, duration, _value); emit Locked(_staker, _value, _nextPeriod, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @dev Probably will be created a new sub-stake but it will be active only one period * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _staker Staker * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, address _staker, uint256 _index, uint256 _value ) internal { SubStakeInfo storage subStake = _info.subStakes[_index]; (, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod); // create temporary sub-stake for current or previous committed periods // to leave locked amount in this period unchanged if (_info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod <= _currentPeriod || _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod <= _currentPeriod) { saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue); } subStake.lockedValue += uint128(_value); // all new locks should start from the next period subStake.firstPeriod = _nextPeriod; emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod); } /** * @notice Checks that last period of sub-stake is greater than the current period * @param _info Staker structure * @param _subStake Sub-stake structure * @param _currentPeriod Current period * @return startPeriod Start period. Use in the calculation of the last period of the sub stake * @return lastPeriod Last period of the sub stake */ function checkLastPeriodOfSubStake( StakerInfo storage _info, SubStakeInfo storage _subStake, uint16 _currentPeriod ) internal view returns (uint16 startPeriod, uint16 lastPeriod) { startPeriod = getStartPeriod(_info, _currentPeriod); lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod); // The sub stake must be active at least in the next period require(lastPeriod > _currentPeriod); } /** * @notice Save sub stake. First tries to override inactive sub stake * @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded * @param _info Staker structure * @param _firstPeriod First period of the sub stake * @param _lastPeriod Last period of the sub stake * @param _unlockingDuration Duration of the sub stake in periods * @param _lockedValue Amount of locked tokens */ function saveSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint16 _lastPeriod, uint16 _unlockingDuration, uint256 _lockedValue ) internal { for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod != 0 && (_info.currentCommittedPeriod == 0 || subStake.lastPeriod < _info.currentCommittedPeriod) && (_info.nextCommittedPeriod == 0 || subStake.lastPeriod < _info.nextCommittedPeriod)) { subStake.firstPeriod = _firstPeriod; subStake.lastPeriod = _lastPeriod; subStake.unlockingDuration = _unlockingDuration; subStake.lockedValue = uint128(_lockedValue); return; } } require(_info.subStakes.length < MAX_SUB_STAKES); _info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _unlockingDuration, uint128(_lockedValue))); } /** * @notice Divide sub stake into two parts * @param _index Index of the sub stake * @param _newValue New sub stake value * @param _additionalDuration Amount of periods for extending sub stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; require(_newValue >= minAllowableLockedTokens && _additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); uint256 oldValue = subStake.lockedValue; subStake.lockedValue = uint128(oldValue.sub(_newValue)); require(subStake.lockedValue >= minAllowableLockedTokens); uint16 requestedPeriods = subStake.unlockingDuration.add16(_additionalDuration); saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue); emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _additionalDuration); emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _additionalDuration Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Incorrect parameters require(_additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); subStake.unlockingDuration = subStake.unlockingDuration.add16(_additionalDuration); // if the sub stake ends in the next committed period then reset the `lastPeriod` field if (lastPeriod == startPeriod) { subStake.lastPeriod = 0; } // The extended sub stake must not be less than the minimum value require(uint32(lastPeriod - currentPeriod) + _additionalDuration >= minLockedPeriods); emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _additionalDuration); emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _additionalDuration); } /** * @notice Merge two sub-stakes into one if their last periods are equal * @dev It's possible that both sub-stakes will be active after this transaction. * But only one of them will be active until next call `commitToNextPeriod` (in the next period) * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker { require(_index1 != _index2); // must be different sub-stakes StakerInfo storage info = stakerInfo[msg.sender]; SubStakeInfo storage subStake1 = info.subStakes[_index1]; SubStakeInfo storage subStake2 = info.subStakes[_index2]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod); (, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod); // both sub-stakes must have equal last period to be mergeable require(lastPeriod1 == lastPeriod2); emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1); if (subStake1.firstPeriod == subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = 1; subStake2.unlockingDuration = 0; } else if (subStake1.firstPeriod > subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = subStake1.firstPeriod - 1; subStake2.unlockingDuration = 0; } else { subStake2.lockedValue += subStake1.lockedValue; subStake1.lastPeriod = subStake2.firstPeriod - 1; subStake1.unlockingDuration = 0; } } /** * @notice Remove unused sub-stake to decrease gas cost for several methods */ function removeUnusedSubStake(uint16 _index) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; uint256 lastIndex = info.subStakes.length - 1; SubStakeInfo storage subStake = info.subStakes[_index]; require(subStake.lastPeriod != 0 && (info.currentCommittedPeriod == 0 || subStake.lastPeriod < info.currentCommittedPeriod) && (info.nextCommittedPeriod == 0 || subStake.lastPeriod < info.nextCommittedPeriod)); if (_index != lastIndex) { SubStakeInfo storage lastSubStake = info.subStakes[lastIndex]; subStake.firstPeriod = lastSubStake.firstPeriod; subStake.lastPeriod = lastSubStake.lastPeriod; subStake.unlockingDuration = lastSubStake.unlockingDuration; subStake.lockedValue = lastSubStake.lockedValue; } info.subStakes.pop(); } /** * @notice Withdraw available amount of tokens to staker * @param _value Amount of tokens to withdraw */ function withdraw(uint256 _value) external onlyStaker { uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[msg.sender]; // the max locked tokens in most cases will be in the current period // but when the staker locks more then we should use the next period uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod), getLockedTokens(info, currentPeriod, currentPeriod)); require(_value <= info.value.sub(lockedTokens)); info.value -= _value; addSnapshot(info, - int256(_value)); token.safeTransfer(msg.sender, _value); emit Withdrawn(msg.sender, _value); // unbond worker if staker withdraws last portion of NU if (info.value == 0 && info.nextCommittedPeriod == 0 && info.worker != address(0)) { stakerFromWorker[info.worker] = address(0); info.worker = address(0); emit WorkerBonded(msg.sender, address(0), currentPeriod); } } /** * @notice Make a commitment to the next period and mint for the previous period */ function commitToNextPeriod() external isInitialized { address staker = stakerFromWorker[msg.sender]; StakerInfo storage info = stakerInfo[staker]; // Staker must have a stake to make a commitment require(info.value > 0); // Only worker with real address can make a commitment require(msg.sender == tx.origin); migrate(staker); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; // the period has already been committed require(info.nextCommittedPeriod != nextPeriod); uint16 lastCommittedPeriod = getLastCommittedPeriod(staker); (uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker); uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); require(lockedTokens > 0); _lockedPerPeriod[nextPeriod] += lockedTokens; info.currentCommittedPeriod = info.nextCommittedPeriod; info.nextCommittedPeriod = nextPeriod; decreaseSubStakesDuration(info, nextPeriod); // staker was inactive for several periods if (lastCommittedPeriod < currentPeriod) { info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod)); } policyManager.ping(staker, processedPeriod1, processedPeriod2, nextPeriod); emit CommitmentMade(staker, nextPeriod, lockedTokens); } /** * @notice Migrate from the old period length to the new one. Can be done only once * @param _staker Staker */ function migrate(address _staker) public { StakerInfo storage info = stakerInfo[_staker]; // check that provided address is/was a staker require(info.subStakes.length != 0 || info.lastCommittedPeriod != 0); if (info.flags.bitSet(MIGRATED_INDEX)) { return; } // reset state info.currentCommittedPeriod = 0; info.nextCommittedPeriod = 0; // maintain case when no more sub-stakes and need to avoid re-registering this staker during deposit info.lastCommittedPeriod = 1; info.workerStartPeriod = recalculatePeriod(info.workerStartPeriod); delete info.pastDowntime; // recalculate all sub-stakes uint16 currentPeriod = getCurrentPeriod(); for (uint256 i = 0; i < info.subStakes.length; i++) { SubStakeInfo storage subStake = info.subStakes[i]; subStake.firstPeriod = recalculatePeriod(subStake.firstPeriod); // sub-stake has fixed last period if (subStake.lastPeriod != 0) { subStake.lastPeriod = recalculatePeriod(subStake.lastPeriod); if (subStake.lastPeriod == 0) { subStake.lastPeriod = 1; } subStake.unlockingDuration = 0; // sub-stake has no fixed ending but possible that with new period length will have } else { uint16 oldCurrentPeriod = uint16(block.timestamp / genesisSecondsPerPeriod); uint16 lastPeriod = recalculatePeriod(oldCurrentPeriod + subStake.unlockingDuration); subStake.unlockingDuration = lastPeriod - currentPeriod; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = lastPeriod; } } } policyManager.migrate(_staker); info.flags = info.flags.toggleBit(MIGRATED_INDEX); emit Migrated(_staker, currentPeriod); } /** * @notice Decrease sub-stakes duration if `windDown` is enabled */ function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal { if (!_info.flags.bitSet(WIND_DOWN_INDEX)) { return; } for (uint256 index = 0; index < _info.subStakes.length; index++) { SubStakeInfo storage subStake = _info.subStakes[index]; if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration--; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = _nextPeriod; } } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment */ function mint() external onlyStaker { // save last committed period to the storage if both periods will be empty after minting // because we won't be able to calculate last committed period // see getLastCommittedPeriod(address) StakerInfo storage info = stakerInfo[msg.sender]; uint16 previousPeriod = getCurrentPeriod() - 1; if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) { info.lastCommittedPeriod = info.nextCommittedPeriod; } (uint16 processedPeriod1, uint16 processedPeriod2) = mint(msg.sender); if (processedPeriod1 != 0 || processedPeriod2 != 0) { policyManager.ping(msg.sender, processedPeriod1, processedPeriod2, 0); } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment * @param _staker Staker * @return processedPeriod1 Processed period: currentCommittedPeriod or zero * @return processedPeriod2 Processed period: nextCommittedPeriod or zero */ function mint(address _staker) internal returns (uint16 processedPeriod1, uint16 processedPeriod2) { uint16 currentPeriod = getCurrentPeriod(); uint16 previousPeriod = currentPeriod - 1; StakerInfo storage info = stakerInfo[_staker]; if (info.nextCommittedPeriod == 0 || info.currentCommittedPeriod == 0 && info.nextCommittedPeriod > previousPeriod || info.currentCommittedPeriod > previousPeriod) { return (0, 0); } uint16 startPeriod = getStartPeriod(info, currentPeriod); uint256 reward = 0; bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); if (info.currentCommittedPeriod != 0) { reward = mint(info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod1 = info.currentCommittedPeriod; info.currentCommittedPeriod = 0; if (reStake) { _lockedPerPeriod[info.nextCommittedPeriod] += reward; } } if (info.nextCommittedPeriod <= previousPeriod) { reward += mint(info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod2 = info.nextCommittedPeriod; info.nextCommittedPeriod = 0; } info.value += reward; if (info.flags.bitSet(MEASURE_WORK_INDEX)) { info.completedWork += reward; } addSnapshot(info, int256(reward)); emit Minted(_staker, previousPeriod, reward); } /** * @notice Calculate reward for one period * @param _info Staker structure * @param _mintingPeriod Period for minting calculation * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period */ function mint( StakerInfo storage _info, uint16 _mintingPeriod, uint16 _currentPeriod, uint16 _startPeriod, bool _reStake ) internal returns (uint256 reward) { reward = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) { uint256 subStakeReward = mint( _currentPeriod, subStake.lockedValue, _lockedPerPeriod[_mintingPeriod], lastPeriod.sub16(_mintingPeriod)); reward += subStakeReward; if (_reStake) { subStake.lockedValue += uint128(subStakeReward); } } } return reward; } //-------------------------Slashing------------------------- /** * @notice Slash the staker's stake and reward the investigator * @param _staker Staker's address * @param _penalty Penalty * @param _investigator Investigator * @param _reward Reward for the investigator */ function slashStaker( address _staker, uint256 _penalty, address _investigator, uint256 _reward ) public isInitialized { require(msg.sender == address(adjudicator)); require(_penalty > 0); StakerInfo storage info = stakerInfo[_staker]; require(info.flags.bitSet(MIGRATED_INDEX)); if (info.value <= _penalty) { _penalty = info.value; } info.value -= _penalty; if (_reward > _penalty) { _reward = _penalty; } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; uint16 startPeriod = getStartPeriod(info, currentPeriod); (uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) = getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod); // Decrease the stake if amount of locked tokens in the current period more than staker has uint256 lockedTokens = currentLock + currentAndNextLock; if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex); } // Decrease the stake if amount of locked tokens in the next period more than staker has if (nextLock > 0) { lockedTokens = nextLock + currentAndNextLock - (currentAndNextLock > info.value ? currentAndNextLock - info.value : 0); if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES); } } emit Slashed(_staker, _penalty, _investigator, _reward); if (_penalty > _reward) { unMint(_penalty - _reward); } // TODO change to withdrawal pattern (#1499) if (_reward > 0) { token.safeTransfer(_investigator, _reward); } addSnapshot(info, - int256(_penalty)); } /** * @notice Get the value of locked tokens for a staker in the current and the next period * and find the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _startPeriod Pre-calculated start period * @return currentLock Amount of tokens that locked in the current period and unlocked in the next period * @return nextLock Amount of tokens that locked in the next period and not locked in the current period * @return currentAndNextLock Amount of tokens that locked in the current period and in the next period * @return shortestSubStakeIndex Index of the shortest sub stake */ function getLockedTokensAndShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, uint16 _startPeriod ) internal view returns ( uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex ) { uint16 minDuration = MAX_UINT16; uint16 minLastPeriod = MAX_UINT16; shortestSubStakeIndex = MAX_SUB_STAKES; currentLock = 0; nextLock = 0; currentAndNextLock = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _nextPeriod) { currentAndNextLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod) { currentLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _nextPeriod && lastPeriod >= _nextPeriod) { nextLock += subStake.lockedValue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minLastPeriod || lastPeriod == minLastPeriod && duration < minDuration)) { shortestSubStakeIndex = i; minDuration = duration; minLastPeriod = lastPeriod; } } } /** * @notice Decrease short sub stakes * @param _info Staker structure * @param _penalty Penalty rate * @param _decreasePeriod The period when the decrease begins * @param _startPeriod Pre-calculated start period * @param _shortestSubStakeIndex Index of the shortest period */ function decreaseSubStakes( StakerInfo storage _info, uint256 _penalty, uint16 _decreasePeriod, uint16 _startPeriod, uint256 _shortestSubStakeIndex ) internal { SubStakeInfo storage shortestSubStake = _info.subStakes[0]; uint16 minSubStakeLastPeriod = MAX_UINT16; uint16 minSubStakeDuration = MAX_UINT16; while(_penalty > 0) { if (_shortestSubStakeIndex < MAX_SUB_STAKES) { shortestSubStake = _info.subStakes[_shortestSubStakeIndex]; minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod); minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod; _shortestSubStakeIndex = MAX_SUB_STAKES; } else { (shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) = getShortestSubStake(_info, _decreasePeriod, _startPeriod); } if (minSubStakeDuration == MAX_UINT16) { break; } uint256 appliedPenalty = _penalty; if (_penalty < shortestSubStake.lockedValue) { shortestSubStake.lockedValue -= uint128(_penalty); saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod); _penalty = 0; } else { shortestSubStake.lastPeriod = _decreasePeriod - 1; _penalty -= shortestSubStake.lockedValue; appliedPenalty = shortestSubStake.lockedValue; } if (_info.currentCommittedPeriod >= _decreasePeriod && _info.currentCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty; } if (_info.nextCommittedPeriod >= _decreasePeriod && _info.nextCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty; } } } /** * @notice Get the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period * @return shortestSubStake The shortest sub stake * @return minSubStakeDuration Duration of the shortest sub stake * @return minSubStakeLastPeriod Last period of the shortest sub stake */ function getShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _startPeriod ) internal view returns ( SubStakeInfo storage shortestSubStake, uint16 minSubStakeDuration, uint16 minSubStakeLastPeriod ) { shortestSubStake = shortestSubStake; minSubStakeDuration = MAX_UINT16; minSubStakeLastPeriod = MAX_UINT16; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minSubStakeLastPeriod || lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration)) { shortestSubStake = subStake; minSubStakeDuration = duration; minSubStakeLastPeriod = lastPeriod; } } } /** * @notice Save the old sub stake values to prevent decreasing reward for the previous period * @dev Saving happens only if the previous period is committed * @param _info Staker structure * @param _firstPeriod First period of the old sub stake * @param _lockedValue Locked value of the old sub stake * @param _currentPeriod Current period, when the old sub stake is already unlocked */ function saveOldSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint256 _lockedValue, uint16 _currentPeriod ) internal { // Check that the old sub stake should be saved bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod < _currentPeriod; bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod < _currentPeriod; bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod; bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod; if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) { return; } // Try to find already existent proper old sub stake uint16 previousPeriod = _currentPeriod - 1; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod == previousPeriod && ((crosscurrentCommittedPeriod == (oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) && (crossnextCommittedPeriod == (oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod)))) { subStake.lockedValue += uint128(_lockedValue); return; } } saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue); } //-------------Additional getters for stakers info------------- /** * @notice Return the length of the array of stakers */ function getStakersLength() external view returns (uint256) { return stakers.length; } /** * @notice Return the length of the array of sub stakes */ function getSubStakesLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].subStakes.length; } /** * @notice Return the information about sub stake */ function getSubStakeInfo(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (SubStakeInfo) // TODO "virtual" only for tests, probably will be removed after #1512 external view virtual returns ( uint16 firstPeriod, uint16 lastPeriod, uint16 unlockingDuration, uint128 lockedValue ) { SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index]; firstPeriod = info.firstPeriod; lastPeriod = info.lastPeriod; unlockingDuration = info.unlockingDuration; lockedValue = info.lockedValue; } /** * @notice Return the length of the array of past downtime */ function getPastDowntimeLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].pastDowntime.length; } /** * @notice Return the information about past downtime */ function getPastDowntime(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (Downtime) external view returns (uint16 startPeriod, uint16 endPeriod) { Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index]; startPeriod = downtime.startPeriod; endPeriod = downtime.endPeriod; } //------------------ ERC900 connectors ---------------------- function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){ return stakerInfo[_owner].history.getValueAt(_blockNumber); } function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){ return balanceHistory.getValueAt(_blockNumber); } function supportsHistory() external pure override returns (bool){ return true; } //------------------------Upgradeable------------------------ /** * @dev Get StakerInfo structure by delegatecall */ function delegateGetStakerInfo(address _target, bytes32 _staker) internal returns (StakerInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0); assembly { result := memoryAddress } } /** * @dev Get SubStakeInfo structure by delegatecall */ function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index) internal returns (SubStakeInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get Downtime structure by delegatecall */ function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index) internal returns (Downtime memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getPastDowntime.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(delegateGet(_testTarget, this.lockedPerPeriod.selector, bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod(RESERVED_PERIOD)); require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) == stakerFromWorker[address(0)]); require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length); if (stakers.length == 0) { return; } address stakerAddress = stakers[0]; require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress); StakerInfo storage info = stakerInfo[stakerAddress]; bytes32 staker = bytes32(uint256(stakerAddress)); StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker); require(infoToCheck.value == info.value && infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod && infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod && infoToCheck.flags == info.flags && infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod && infoToCheck.completedWork == info.completedWork && infoToCheck.worker == info.worker && infoToCheck.workerStartPeriod == info.workerStartPeriod); require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) == info.pastDowntime.length); for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) { Downtime storage downtime = info.pastDowntime[i]; Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i); require(downtimeToCheck.startPeriod == downtime.startPeriod && downtimeToCheck.endPeriod == downtime.endPeriod); } require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length); for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) { SubStakeInfo storage subStakeInfo = info.subStakes[i]; SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i); require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod && subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod && subStakeInfoToCheck.unlockingDuration == subStakeInfo.unlockingDuration && subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue); } // it's not perfect because checks not only slot value but also decoding // at least without additional functions require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) == totalStakedForAt(stakerAddress, block.number)); require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) == totalStakedAt(block.number)); if (info.worker != address(0)) { require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) == stakerFromWorker[info.worker]); } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // Create fake period _lockedPerPeriod[RESERVED_PERIOD] = 111; // Create fake worker stakerFromWorker[address(0)] = address(this); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; // Minimum interface to interact with Aragon's Aggregator interface IERC900History { function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256); function totalStakedAt(uint256 blockNumber) external view returns (uint256); function supportsHistory() external pure returns (bool); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./NuCypherToken.sol"; import "../zeppelin/math/Math.sol"; import "./proxy/Upgradeable.sol"; import "./lib/AdditionalMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @title Issuer * @notice Contract for calculation of issued tokens * @dev |v3.4.1| */ abstract contract Issuer is Upgradeable { using SafeERC20 for NuCypherToken; using AdditionalMath for uint32; event Donated(address indexed sender, uint256 value); /// Issuer is initialized with a reserved reward event Initialized(uint256 reservedReward); uint128 constant MAX_UINT128 = uint128(0) - 1; NuCypherToken public immutable token; uint128 public immutable totalSupply; // d * k2 uint256 public immutable mintingCoefficient; // k1 uint256 public immutable lockDurationCoefficient1; // k2 uint256 public immutable lockDurationCoefficient2; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; // kmax uint16 public immutable maximumRewardedPeriods; uint256 public immutable firstPhaseMaxIssuance; uint256 public immutable firstPhaseTotalSupply; /** * Current supply is used in the minting formula and is stored to prevent different calculation * for stakers which get reward in the same period. There are two values - * supply for previous period (used in formula) and supply for current period which accumulates value * before end of period. */ uint128 public previousPeriodSupply; uint128 public currentPeriodSupply; uint16 public currentMintingPeriod; /** * @notice Constructor sets address of token contract and coefficients for minting * @dev Minting formula for one sub-stake in one period for the first phase firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 * @dev Minting formula for one sub-stake in one period for the second phase (totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance ) { uint256 localTotalSupply = _token.totalSupply(); require(localTotalSupply > 0 && _issuanceDecayCoefficient != 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _lockDurationCoefficient1 != 0 && _lockDurationCoefficient2 != 0 && _maximumRewardedPeriods != 0); require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported"); uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1; uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2; require(maxLockDurationCoefficient > _maximumRewardedPeriods && localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 && // worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient && // worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`, // when currentSupply == 0, lockedValue == totalSupply localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply == maxLockDurationCoefficient, "Specified parameters cause overflow"); require(maxLockDurationCoefficient <= _lockDurationCoefficient2, "Resulting locking duration coefficient must be less than 1"); require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase"); require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high"); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); lockDurationCoefficient1 = _lockDurationCoefficient1; lockDurationCoefficient2 = _lockDurationCoefficient2; maximumRewardedPeriods = _maximumRewardedPeriods; firstPhaseTotalSupply = _firstPhaseTotalSupply; firstPhaseMaxIssuance = _firstPhaseMaxIssuance; totalSupply = uint128(localTotalSupply); mintingCoefficient = localMintingCoefficient; } /** * @dev Checks contract initialization */ modifier isInitialized() { require(currentMintingPeriod != 0); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod); } /** * @notice Initialize reserved tokens for reward */ function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner { require(currentMintingPeriod == 0); // Reserved reward must be sufficient for at least one period of the first phase require(firstPhaseMaxIssuance <= _reservedReward); currentMintingPeriod = getCurrentPeriod(); currentPeriodSupply = totalSupply - uint128(_reservedReward); previousPeriodSupply = currentPeriodSupply; token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward); emit Initialized(_reservedReward); } /** * @notice Function to mint tokens for one period. * @param _currentPeriod Current period number. * @param _lockedValue The amount of tokens that were locked by user in specified period. * @param _totalLockedValue The amount of tokens that were locked by all users in specified period. * @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period. * @return amount Amount of minted tokens. */ function mint( uint16 _currentPeriod, uint256 _lockedValue, uint256 _totalLockedValue, uint16 _allLockedPeriods ) internal returns (uint256 amount) { if (currentPeriodSupply == totalSupply) { return 0; } if (_currentPeriod > currentMintingPeriod) { previousPeriodSupply = currentPeriodSupply; currentMintingPeriod = _currentPeriod; } uint256 currentReward; uint256 coefficient; // first phase // firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2) if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) { currentReward = firstPhaseMaxIssuance; coefficient = lockDurationCoefficient2; // second phase // (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2) } else { currentReward = totalSupply - previousPeriodSupply; coefficient = mintingCoefficient; } uint256 allLockedPeriods = AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1; amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) / (_totalLockedValue * coefficient); // rounding the last reward uint256 maxReward = getReservedReward(); if (amount == 0) { amount = 1; } else if (amount > maxReward) { amount = maxReward; } currentPeriodSupply += uint128(amount); } /** * @notice Return tokens for future minting * @param _amount Amount of tokens */ function unMint(uint256 _amount) internal { previousPeriodSupply -= uint128(_amount); currentPeriodSupply -= uint128(_amount); } /** * @notice Donate sender's tokens. Amount of tokens will be returned for future minting * @param _value Amount to donate */ function donate(uint256 _value) external isInitialized { token.safeTransferFrom(msg.sender, address(this), _value); unMint(_value); emit Donated(msg.sender, _value); } /** * @notice Returns the number of tokens that can be minted */ function getReservedReward() public view returns (uint256) { return totalSupply - currentPeriodSupply; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod); require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply); require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // recalculate currentMintingPeriod if needed if (currentMintingPeriod > getCurrentPeriod()) { currentMintingPeriod = recalculatePeriod(currentMintingPeriod); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/ERC20.sol"; import "../zeppelin/token/ERC20/ERC20Detailed.sol"; /** * @title NuCypherToken * @notice ERC20 token * @dev Optional approveAndCall() functionality to notify a contract if an approve() has occurred. */ contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) { /** * @notice Set amount of tokens * @param _totalSupplyOfTokens Total number of tokens */ constructor (uint256 _totalSupplyOfTokens) { _mint(msg.sender, _totalSupplyOfTokens); } /** * @notice Approves and then calls the receiving contract * * @dev call the receiveApproval function on the contract you want to be notified. * receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) */ function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { approve(_spender, _value); TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * @dev Interface to use the receiveApproval method */ interface TokenRecipient { /** * @notice Receives a notification of approval of the transfer * @param _from Sender of approval * @param _value The amount of tokens to be spent * @param _tokenContract Address of the token contract * @param _extraData Extra data */ function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view override returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender'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 override 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); _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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 override returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; /** * @notice Base contract for upgradeable contract * @dev Inherited contract should implement verifyState(address) method by checking storage variables * (see verifyState(address) in Dispatcher). Also contract should implement finishUpgrade(address) * if it is using constructor parameters by coping this parameters to the dispatcher storage */ abstract contract Upgradeable is Ownable { event StateVerified(address indexed testTarget, address sender); event UpgradeFinished(address indexed target, address sender); /** * @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher * Stored data actually lives in the Dispatcher * However the storage layout is specified here in the implementing contracts */ address public target; /** * @dev Previous contract address (if available). Used for rollback */ address public previousTarget; /** * @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value */ uint8 public isUpgrade; /** * @dev Guarantees that next slot will be separated from the previous */ uint256 stubSlot; /** * @dev Constants for `isUpgrade` field */ uint8 constant UPGRADE_FALSE = 1; uint8 constant UPGRADE_TRUE = 2; /** * @dev Checks that function executed while upgrading * Recommended to add to `verifyState` and `finishUpgrade` methods */ modifier onlyWhileUpgrading() { require(isUpgrade == UPGRADE_TRUE); _; } /** * @dev Method for verifying storage state. * Should check that new target contract returns right storage value */ function verifyState(address _testTarget) public virtual onlyWhileUpgrading { emit StateVerified(_testTarget, msg.sender); } /** * @dev Copy values from the new target to the current storage * @param _target New target contract address */ function finishUpgrade(address _target) public virtual onlyWhileUpgrading { emit UpgradeFinished(_target, msg.sender); } /** * @dev Base method to get data * @param _target Target to call * @param _selector Method selector * @param _numberOfArguments Number of used arguments * @param _argument1 First method argument * @param _argument2 Second method argument * @return memoryAddress Address in memory where the data is located */ function delegateGetData( address _target, bytes4 _selector, uint8 _numberOfArguments, bytes32 _argument1, bytes32 _argument2 ) internal returns (bytes32 memoryAddress) { assembly { memoryAddress := mload(0x40) mstore(memoryAddress, _selector) if gt(_numberOfArguments, 0) { mstore(add(memoryAddress, 0x04), _argument1) } if gt(_numberOfArguments, 1) { mstore(add(memoryAddress, 0x24), _argument2) } switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0) case 0 { revert(memoryAddress, 0) } default { returndatacopy(memoryAddress, 0x0, returndatasize()) } } } /** * @dev Call "getter" without parameters. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with one parameter. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector, bytes32 _argument) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with two parameters. * Result should not exceed 32 bytes */ function delegateGet( address _target, bytes4 _selector, bytes32 _argument1, bytes32 _argument2 ) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2); assembly { result := mload(memoryAddress) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () { _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 virtual 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; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/math/SafeMath.sol"; /** * @notice Additional math operations */ library AdditionalMath { using SafeMath for uint256; function max16(uint16 a, uint16 b) internal pure returns (uint16) { return a >= b ? a : b; } function min16(uint16 a, uint16 b) internal pure returns (uint16) { return a < b ? a : b; } /** * @notice Division and ceil */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return (a.add(b) - 1) / b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.add(uint256(b)); } else { return a.sub(uint256(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.sub(uint256(b)); } else { return a.add(uint256(-b)); } } /** * @dev Multiplies two numbers, throws on overflow. */ function mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } /** * @dev Adds two numbers, throws on overflow. */ function add16(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub16(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return add16(a, uint16(b)); } else { return sub16(a, uint16(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return sub16(a, uint16(b)); } else { return add16(a, uint16(-b)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @dev Taken from https://github.com/ethereum/solidity-examples/blob/master/src/bits/Bits.sol */ library Bits { uint256 internal constant ONE = uint256(1); /** * @notice Sets the bit at the given 'index' in 'self' to: * '1' - if the bit is '0' * '0' - if the bit is '1' * @return The modified value */ function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) { return self ^ ONE << index; } /** * @notice Get the value of the bit at the given 'index' in 'self'. */ function bit(uint256 self, uint8 index) internal pure returns (uint8) { return uint8(self >> index & 1); } /** * @notice Check if the bit at the given 'index' in 'self' is set. * @return 'true' - if the value of the bit is '1', * 'false' - if the value of the bit is '0' */ function bitSet(uint256 self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @title Snapshot * @notice Manages snapshots of size 128 bits (32 bits for timestamp, 96 bits for value) * 96 bits is enough for storing NU token values, and 32 bits should be OK for block numbers * @dev Since each storage slot can hold two snapshots, new slots are allocated every other TX. Thus, gas cost of adding snapshots is 51400 and 36400 gas, alternately. * Based on Aragon's Checkpointing (https://https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/Checkpointing.sol) * On average, adding snapshots spends ~6500 less gas than the 256-bit checkpoints of Aragon's Checkpointing */ library Snapshot { function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) { return uint128(uint256(_time) << 96 | uint256(_value)); } function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){ time = uint32(bytes4(bytes16(_snapshot))); value = uint96(_snapshot); } function addSnapshot(uint128[] storage _self, uint256 _value) internal { addSnapshot(_self, block.number, _value); } function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal { uint256 length = _self.length; if (length != 0) { (uint32 currentTime, ) = decodeSnapshot(_self[length - 1]); if (uint32(_time) == currentTime) { _self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value)); return; } else if (uint32(_time) < currentTime){ revert(); } } _self.push(encodeSnapshot(uint32(_time), uint96(_value))); } function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) { uint256 length = _self.length; if (length > 0) { return decodeSnapshot(_self[length - 1]); } return (0, 0); } function lastValue(uint128[] storage _self) internal view returns (uint96) { (, uint96 value) = lastSnapshot(_self); return value; } function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) { uint32 _time = uint32(_time256); uint256 length = _self.length; // Short circuit if there's no checkpoints yet // Note that this also lets us avoid using SafeMath later on, as we've established that // there must be at least one checkpoint if (length == 0) { return 0; } // Check last checkpoint uint256 lastIndex = length - 1; (uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]); if (_time >= snapshotTime) { return snapshotValue; } // Check first checkpoint (if not already checked with the above check on last) (snapshotTime, snapshotValue) = decodeSnapshot(_self[0]); if (length == 1 || _time < snapshotTime) { return 0; } // Do binary search // As we've already checked both ends, we don't need to check the last checkpoint again uint256 low = 0; uint256 high = lastIndex - 1; uint32 midTime; uint96 midValue; while (high > low) { uint256 mid = (high + low + 1) / 2; // average, ceil round (midTime, midValue) = decodeSnapshot(_self[mid]); if (_time > midTime) { low = mid; } else if (_time < midTime) { // Note that we don't need SafeMath here because mid must always be greater than 0 // from the while condition high = mid - 1; } else { // _time == midTime return midValue; } } (, snapshotValue) = decodeSnapshot(_self[low]); return snapshotValue; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface IForwarder { function isForwarder() external pure returns (bool); function canForward(address sender, bytes calldata evmCallScript) external view returns (bool); function forward(bytes calldata evmCallScript) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface TokenManager { function mint(address _receiver, uint256 _amount) external; function issue(uint256 _amount) external; function assign(address _receiver, uint256 _amount) external; function burn(address _holder, uint256 _amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; import "./IForwarder.sol"; // Interface for Voting contract, as found in https://github.com/aragon/aragon-apps/blob/master/apps/voting/contracts/Voting.sol interface Voting is IForwarder{ enum VoterState { Absent, Yea, Nay } // Public getters function token() external returns (address); function supportRequiredPct() external returns (uint64); function minAcceptQuorumPct() external returns (uint64); function voteTime() external returns (uint64); function votesLength() external returns (uint256); // Setters function changeSupportRequiredPct(uint64 _supportRequiredPct) external; function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external; // Creating new votes function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId); function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided) external returns (uint256 voteId); // Voting function canVote(uint256 _voteId, address _voter) external view returns (bool); function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external; // Executing a passed vote function canExecute(uint256 _voteId) external view returns (bool); function executeVote(uint256 _voteId) external; // Additional info function getVote(uint256 _voteId) external view returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes memory script ); function getVoterState(uint256 _voteId, address _voter) external view returns (VoterState); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; /** * @notice Multi-signature contract with off-chain signing */ contract MultiSig { using SafeMath for uint256; event Executed(address indexed sender, uint256 indexed nonce, address indexed destination, uint256 value); event OwnerAdded(address indexed owner); event OwnerRemoved(address indexed owner); event RequirementChanged(uint16 required); uint256 constant public MAX_OWNER_COUNT = 50; uint256 public nonce; uint8 public required; mapping (address => bool) public isOwner; address[] public owners; /** * @notice Only this contract can call method */ modifier onlyThisContract() { require(msg.sender == address(this)); _; } receive() external payable {} /** * @param _required Number of required signings * @param _owners List of initial owners. */ constructor (uint8 _required, address[] memory _owners) { require(_owners.length <= MAX_OWNER_COUNT && _required <= _owners.length && _required > 0); for (uint256 i = 0; i < _owners.length; i++) { address owner = _owners[i]; require(!isOwner[owner] && owner != address(0)); isOwner[owner] = true; } owners = _owners; required = _required; } /** * @notice Get unsigned hash for transaction parameters * @dev Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191 * @param _sender Trustee who will execute the transaction * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data * @param _nonce Nonce */ function getUnsignedTransactionHash( address _sender, address _destination, uint256 _value, bytes memory _data, uint256 _nonce ) public view returns (bytes32) { return keccak256( abi.encodePacked(byte(0x19), byte(0), address(this), _sender, _destination, _value, _data, _nonce)); } /** * @dev Note that address recovered from signatures must be strictly increasing * @param _sigV Array of signatures values V * @param _sigR Array of signatures values R * @param _sigS Array of signatures values S * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data */ function execute( uint8[] calldata _sigV, bytes32[] calldata _sigR, bytes32[] calldata _sigS, address _destination, uint256 _value, bytes calldata _data ) external { require(_sigR.length >= required && _sigR.length == _sigS.length && _sigR.length == _sigV.length); bytes32 txHash = getUnsignedTransactionHash(msg.sender, _destination, _value, _data, nonce); address lastAdd = address(0); for (uint256 i = 0; i < _sigR.length; i++) { address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]); require(recovered > lastAdd && isOwner[recovered]); lastAdd = recovered; } emit Executed(msg.sender, nonce, _destination, _value); nonce = nonce.add(1); (bool callSuccess,) = _destination.call{value: _value}(_data); require(callSuccess); } /** * @notice Allows to add a new owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of new owner */ function addOwner(address _owner) external onlyThisContract { require(owners.length < MAX_OWNER_COUNT && _owner != address(0) && !isOwner[_owner]); isOwner[_owner] = true; owners.push(_owner); emit OwnerAdded(_owner); } /** * @notice Allows to remove an owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of owner */ function removeOwner(address _owner) external onlyThisContract { require(owners.length > required && isOwner[_owner]); isOwner[_owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) { if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } } owners.pop(); emit OwnerRemoved(_owner); } /** * @notice Returns the number of owners of this MultiSig */ function getNumberOfOwners() external view returns (uint256) { return owners.length; } /** * @notice Allows to change the number of required signatures * @dev Transaction has to be sent by `execute` method * @param _required Number of required signatures */ function changeRequirement(uint8 _required) external onlyThisContract { require(_required <= owners.length && _required > 0); required = _required; emit RequirementChanged(_required); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; import "../zeppelin/utils/Address.sol"; import "./lib/AdditionalMath.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./NuCypherToken.sol"; import "./proxy/Upgradeable.sol"; /** * @title PolicyManager * @notice Contract holds policy data and locks accrued policy fees * @dev |v6.3.1| */ contract PolicyManager is Upgradeable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using AdditionalMath for int256; using AdditionalMath for uint16; using Address for address payable; event PolicyCreated( bytes16 indexed policyId, address indexed sponsor, address indexed owner, uint256 feeRate, uint64 startTimestamp, uint64 endTimestamp, uint256 numberOfNodes ); event ArrangementRevoked( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event RefundForArrangement( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event PolicyRevoked(bytes16 indexed policyId, address indexed sender, uint256 value); event RefundForPolicy(bytes16 indexed policyId, address indexed sender, uint256 value); event MinFeeRateSet(address indexed node, uint256 value); // TODO #1501 // Range range event FeeRateRangeSet(address indexed sender, uint256 min, uint256 defaultValue, uint256 max); event Withdrawn(address indexed node, address indexed recipient, uint256 value); struct ArrangementInfo { address node; uint256 indexOfDowntimePeriods; uint16 lastRefundedPeriod; } struct Policy { bool disabled; address payable sponsor; address owner; uint128 feeRate; uint64 startTimestamp; uint64 endTimestamp; uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; ArrangementInfo[] arrangements; } struct NodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; mapping (uint16 => int256) stub; // former slot for feeDelta mapping (uint16 => int256) feeDelta; } // TODO used only for `delegateGetNodeInfo`, probably will be removed after #1512 struct MemoryNodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; } struct Range { uint128 min; uint128 defaultValue; uint128 max; } bytes16 internal constant RESERVED_POLICY_ID = bytes16(0); address internal constant RESERVED_NODE = address(0); uint256 internal constant MAX_BALANCE = uint256(uint128(0) - 1); // controlled overflow to get max int256 int256 public constant DEFAULT_FEE_DELTA = int256((uint256(0) - 1) >> 1); StakingEscrow public immutable escrow; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; mapping (bytes16 => Policy) public policies; mapping (address => NodeInfo) public nodes; Range public feeRateRange; uint64 public resetTimestamp; /** * @notice Constructor sets address of the escrow contract * @dev Put same address in both inputs variables except when migration is happening * @param _escrowDispatcher Address of escrow dispatcher * @param _escrowImplementation Address of escrow implementation */ constructor(StakingEscrow _escrowDispatcher, StakingEscrow _escrowImplementation) { escrow = _escrowDispatcher; // if the input address is not the StakingEscrow then calling `secondsPerPeriod` will throw error uint32 localSecondsPerPeriod = _escrowImplementation.secondsPerPeriod(); require(localSecondsPerPeriod > 0); secondsPerPeriod = localSecondsPerPeriod; uint32 localgenesisSecondsPerPeriod = _escrowImplementation.genesisSecondsPerPeriod(); require(localgenesisSecondsPerPeriod > 0); genesisSecondsPerPeriod = localgenesisSecondsPerPeriod; // handle case when we deployed new StakingEscrow but not yet upgraded if (_escrowDispatcher != _escrowImplementation) { require(_escrowDispatcher.secondsPerPeriod() == localSecondsPerPeriod || _escrowDispatcher.secondsPerPeriod() == localgenesisSecondsPerPeriod); } } /** * @dev Checks that sender is the StakingEscrow contract */ modifier onlyEscrowContract() { require(msg.sender == address(escrow)); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod); } /** * @notice Register a node * @param _node Node address * @param _period Initial period */ function register(address _node, uint16 _period) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.previousFeePeriod == 0 && _period < getCurrentPeriod()); nodeInfo.previousFeePeriod = _period; } /** * @notice Migrate from the old period length to the new one * @param _node Node address */ function migrate(address _node) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; // with previous period length any previousFeePeriod will be greater than current period // this is a sign of not migrated node require(nodeInfo.previousFeePeriod >= getCurrentPeriod()); nodeInfo.previousFeePeriod = recalculatePeriod(nodeInfo.previousFeePeriod); nodeInfo.feeRate = 0; } /** * @notice Set minimum, default & maximum fee rate for all stakers and all policies ('global fee range') */ // TODO # 1501 // function setFeeRateRange(Range calldata _range) external onlyOwner { function setFeeRateRange(uint128 _min, uint128 _default, uint128 _max) external onlyOwner { require(_min <= _default && _default <= _max); feeRateRange = Range(_min, _default, _max); emit FeeRateRangeSet(msg.sender, _min, _default, _max); } /** * @notice Set the minimum acceptable fee rate (set by staker for their associated worker) * @dev Input value must fall within `feeRateRange` (global fee range) */ function setMinFeeRate(uint256 _minFeeRate) external { require(_minFeeRate >= feeRateRange.min && _minFeeRate <= feeRateRange.max, "The staker's min fee rate must fall within the global fee range"); NodeInfo storage nodeInfo = nodes[msg.sender]; if (nodeInfo.minFeeRate == _minFeeRate) { return; } nodeInfo.minFeeRate = _minFeeRate; emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(NodeInfo storage _nodeInfo) internal view returns (uint256) { // if minFeeRate has not been set or chosen value falls outside the global fee range // a default value is returned instead if (_nodeInfo.minFeeRate == 0 || _nodeInfo.minFeeRate < feeRateRange.min || _nodeInfo.minFeeRate > feeRateRange.max) { return feeRateRange.defaultValue; } else { return _nodeInfo.minFeeRate; } } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(address _node) public view returns (uint256) { NodeInfo storage nodeInfo = nodes[_node]; return getMinFeeRate(nodeInfo); } /** * @notice Create policy * @dev Generate policy id before creation * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _nodes Nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length == msg.value); Policy storage policy = createPolicy(_policyId, _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, int256(feeRate)); policy.arrangements.push(ArrangementInfo(node, 0, 0)); } } /** * @notice Create multiple policies with the same owner, nodes and length * @dev Generate policy ids before creation * @param _policyIds Policy ids * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of all policies in seconds * @param _nodes Nodes that will handle all policies */ function createPolicies( bytes16[] calldata _policyIds, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 && _policyIds.length > 1 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods / _policyIds.length); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length * _policyIds.length == msg.value); for (uint256 i = 0; i < _policyIds.length; i++) { Policy storage policy = createPolicy(_policyIds[i], _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 j = 0; j < _nodes.length; j++) { policy.arrangements.push(ArrangementInfo(_nodes[j], 0, 0)); } } int256 fee = int256(_policyIds.length * feeRate); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, fee); } } /** * @notice Create policy * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _feeRate Fee rate for policy * @param _nodesLength Number of nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, uint128 _feeRate, uint256 _nodesLength ) internal returns (Policy storage policy) { policy = policies[_policyId]; require( _policyId != RESERVED_POLICY_ID && policy.feeRate == 0 && !policy.disabled ); policy.sponsor = msg.sender; policy.startTimestamp = uint64(block.timestamp); policy.endTimestamp = _endTimestamp; policy.feeRate = _feeRate; if (_policyOwner != msg.sender && _policyOwner != address(0)) { policy.owner = _policyOwner; } emit PolicyCreated( _policyId, msg.sender, _policyOwner == address(0) ? msg.sender : _policyOwner, _feeRate, policy.startTimestamp, policy.endTimestamp, _nodesLength ); } /** * @notice Increase fee rate for specified node * @param _currentPeriod Current period * @param _endPeriod End period of policy * @param _node Node that will handle policy * @param _feeRate Fee rate for one policy * @param _overallFeeRate Fee rate for all policies */ function addFeeToNode( uint16 _currentPeriod, uint16 _endPeriod, address _node, uint128 _feeRate, int256 _overallFeeRate ) internal { require(_node != RESERVED_NODE); NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.previousFeePeriod != 0 && nodeInfo.previousFeePeriod < _currentPeriod && _feeRate >= getMinFeeRate(nodeInfo)); // Check default value for feeDelta if (nodeInfo.feeDelta[_currentPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_currentPeriod] = _overallFeeRate; } else { // Overflow protection removed, because ETH total supply less than uint255/int256 nodeInfo.feeDelta[_currentPeriod] += _overallFeeRate; } if (nodeInfo.feeDelta[_endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_endPeriod] = -_overallFeeRate; } else { nodeInfo.feeDelta[_endPeriod] -= _overallFeeRate; } // Reset to default value if needed if (nodeInfo.feeDelta[_currentPeriod] == 0) { nodeInfo.feeDelta[_currentPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[_endPeriod] == 0) { nodeInfo.feeDelta[_endPeriod] = DEFAULT_FEE_DELTA; } } /** * @notice Get policy owner */ function getPolicyOwner(bytes16 _policyId) public view returns (address) { Policy storage policy = policies[_policyId]; return policy.owner == address(0) ? policy.sponsor : policy.owner; } /** * @notice Call from StakingEscrow to update node info once per period. * Set default `feeDelta` value for specified period and update node fee * @param _node Node address * @param _processedPeriod1 Processed period * @param _processedPeriod2 Processed period * @param _periodToSetDefault Period to set */ function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external onlyEscrowContract { NodeInfo storage node = nodes[_node]; // protection from calling not migrated node, see migrate() require(node.previousFeePeriod <= getCurrentPeriod()); if (_processedPeriod1 != 0) { updateFee(node, _processedPeriod1); } if (_processedPeriod2 != 0) { updateFee(node, _processedPeriod2); } // This code increases gas cost for node in trade of decreasing cost for policy sponsor if (_periodToSetDefault != 0 && node.feeDelta[_periodToSetDefault] == 0) { node.feeDelta[_periodToSetDefault] = DEFAULT_FEE_DELTA; } } /** * @notice Update node fee * @param _info Node info structure * @param _period Processed period */ function updateFee(NodeInfo storage _info, uint16 _period) internal { if (_info.previousFeePeriod == 0 || _period <= _info.previousFeePeriod) { return; } for (uint16 i = _info.previousFeePeriod + 1; i <= _period; i++) { int256 delta = _info.feeDelta[i]; if (delta == DEFAULT_FEE_DELTA) { // gas refund _info.feeDelta[i] = 0; continue; } _info.feeRate = _info.feeRate.addSigned(delta); // gas refund _info.feeDelta[i] = 0; } _info.previousFeePeriod = _period; _info.fee += uint128(_info.feeRate); } /** * @notice Withdraw fee by node */ function withdraw() external returns (uint256) { return withdraw(msg.sender); } /** * @notice Withdraw fee by node * @param _recipient Recipient of the fee */ function withdraw(address payable _recipient) public returns (uint256) { NodeInfo storage node = nodes[msg.sender]; uint256 fee = node.fee; require(fee != 0); node.fee = 0; _recipient.sendValue(fee); emit Withdrawn(msg.sender, _recipient, fee); return fee; } /** * @notice Calculate amount of refund * @param _policy Policy * @param _arrangement Arrangement */ function calculateRefundValue(Policy storage _policy, ArrangementInfo storage _arrangement) internal view returns (uint256 refundValue, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { uint16 policyStartPeriod = uint16(_policy.startTimestamp / secondsPerPeriod); uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), uint16(_policy.endTimestamp / secondsPerPeriod)); uint16 minPeriod = AdditionalMath.max16(policyStartPeriod, _arrangement.lastRefundedPeriod); uint16 downtimePeriods = 0; uint256 length = escrow.getPastDowntimeLength(_arrangement.node); uint256 initialIndexOfDowntimePeriods; if (_arrangement.lastRefundedPeriod == 0) { initialIndexOfDowntimePeriods = escrow.findIndexOfPastDowntime(_arrangement.node, policyStartPeriod); } else { initialIndexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods; } for (indexOfDowntimePeriods = initialIndexOfDowntimePeriods; indexOfDowntimePeriods < length; indexOfDowntimePeriods++) { (uint16 startPeriod, uint16 endPeriod) = escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods); if (startPeriod > maxPeriod) { break; } else if (endPeriod < minPeriod) { continue; } downtimePeriods += AdditionalMath.min16(maxPeriod, endPeriod) .sub16(AdditionalMath.max16(minPeriod, startPeriod)) + 1; if (maxPeriod <= endPeriod) { break; } } uint16 lastCommittedPeriod = escrow.getLastCommittedPeriod(_arrangement.node); if (indexOfDowntimePeriods == length && lastCommittedPeriod < maxPeriod) { // Overflow protection removed: // lastCommittedPeriod < maxPeriod and minPeriod <= maxPeriod + 1 downtimePeriods += maxPeriod - AdditionalMath.max16(minPeriod - 1, lastCommittedPeriod); } refundValue = _policy.feeRate * downtimePeriods; lastRefundedPeriod = maxPeriod + 1; } /** * @notice Revoke/refund arrangement/policy by the sponsor * @param _policyId Policy id * @param _node Node that will be excluded or RESERVED_NODE if full policy should be used ( @param _forceRevoke Force revoke arrangement/policy */ function refundInternal(bytes16 _policyId, address _node, bool _forceRevoke) internal returns (uint256 refundValue) { refundValue = 0; Policy storage policy = policies[_policyId]; require(!policy.disabled && policy.startTimestamp >= resetTimestamp); uint16 endPeriod = uint16(policy.endTimestamp / secondsPerPeriod) + 1; uint256 numberOfActive = policy.arrangements.length; uint256 i = 0; for (; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; address node = arrangement.node; if (node == RESERVED_NODE || _node != RESERVED_NODE && _node != node) { numberOfActive--; continue; } uint256 nodeRefundValue; (nodeRefundValue, arrangement.indexOfDowntimePeriods, arrangement.lastRefundedPeriod) = calculateRefundValue(policy, arrangement); if (_forceRevoke) { NodeInfo storage nodeInfo = nodes[node]; // Check default value for feeDelta uint16 lastRefundedPeriod = arrangement.lastRefundedPeriod; if (nodeInfo.feeDelta[lastRefundedPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[lastRefundedPeriod] = -int256(policy.feeRate); } else { nodeInfo.feeDelta[lastRefundedPeriod] -= int256(policy.feeRate); } if (nodeInfo.feeDelta[endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[endPeriod] = int256(policy.feeRate); } else { nodeInfo.feeDelta[endPeriod] += int256(policy.feeRate); } // Reset to default value if needed if (nodeInfo.feeDelta[lastRefundedPeriod] == 0) { nodeInfo.feeDelta[lastRefundedPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[endPeriod] == 0) { nodeInfo.feeDelta[endPeriod] = DEFAULT_FEE_DELTA; } nodeRefundValue += uint256(endPeriod - lastRefundedPeriod) * policy.feeRate; } if (_forceRevoke || arrangement.lastRefundedPeriod >= endPeriod) { arrangement.node = RESERVED_NODE; arrangement.indexOfDowntimePeriods = 0; arrangement.lastRefundedPeriod = 0; numberOfActive--; emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue); } else { emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue); } refundValue += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } address payable policySponsor = policy.sponsor; if (_node == RESERVED_NODE) { if (numberOfActive == 0) { policy.disabled = true; // gas refund policy.sponsor = address(0); policy.owner = address(0); policy.feeRate = 0; policy.startTimestamp = 0; policy.endTimestamp = 0; emit PolicyRevoked(_policyId, msg.sender, refundValue); } else { emit RefundForPolicy(_policyId, msg.sender, refundValue); } } else { // arrangement not found require(i < policy.arrangements.length); } if (refundValue > 0) { policySponsor.sendValue(refundValue); } } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node or RESERVED_NODE if all nodes should be used */ function calculateRefundValueInternal(bytes16 _policyId, address _node) internal view returns (uint256 refundValue) { refundValue = 0; Policy storage policy = policies[_policyId]; require((policy.owner == msg.sender || policy.sponsor == msg.sender) && !policy.disabled); uint256 i = 0; for (; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; if (arrangement.node == RESERVED_NODE || _node != RESERVED_NODE && _node != arrangement.node) { continue; } (uint256 nodeRefundValue,,) = calculateRefundValue(policy, arrangement); refundValue += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } if (_node != RESERVED_NODE) { // arrangement not found require(i < policy.arrangements.length); } } /** * @notice Revoke policy by the sponsor * @param _policyId Policy id */ function revokePolicy(bytes16 _policyId) external returns (uint256 refundValue) { require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, RESERVED_NODE, true); } /** * @notice Revoke arrangement by the sponsor * @param _policyId Policy id * @param _node Node that will be excluded */ function revokeArrangement(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, _node, true); } /** * @notice Get unsigned hash for revocation * @param _policyId Policy id * @param _node Node that will be excluded * @return Revocation hash, EIP191 version 0x45 ('E') */ function getRevocationHash(bytes16 _policyId, address _node) public view returns (bytes32) { return SignatureVerifier.hashEIP191(abi.encodePacked(_policyId, _node), byte(0x45)); } /** * @notice Check correctness of signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner */ function checkOwnerSignature(bytes16 _policyId, address _node, bytes memory _signature) internal view { bytes32 hash = getRevocationHash(_policyId, _node); address recovered = SignatureVerifier.recover(hash, _signature); require(getPolicyOwner(_policyId) == recovered); } /** * @notice Revoke policy or arrangement using owner's signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner, EIP191 version 0x45 ('E') */ function revoke(bytes16 _policyId, address _node, bytes calldata _signature) external returns (uint256 refundValue) { checkOwnerSignature(_policyId, _node, _signature); return refundInternal(_policyId, _node, true); } /** * @notice Refund part of fee by the sponsor * @param _policyId Policy id */ function refund(bytes16 _policyId) external { Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); refundInternal(_policyId, RESERVED_NODE, false); } /** * @notice Refund part of one node's fee by the sponsor * @param _policyId Policy id * @param _node Node address */ function refund(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); return refundInternal(_policyId, _node, false); } /** * @notice Calculate amount of refund * @param _policyId Policy id */ function calculateRefundValue(bytes16 _policyId) external view returns (uint256 refundValue) { return calculateRefundValueInternal(_policyId, RESERVED_NODE); } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node */ function calculateRefundValue(bytes16 _policyId, address _node) external view returns (uint256 refundValue) { require(_node != RESERVED_NODE); return calculateRefundValueInternal(_policyId, _node); } /** * @notice Get number of arrangements in the policy * @param _policyId Policy id */ function getArrangementsLength(bytes16 _policyId) external view returns (uint256) { return policies[_policyId].arrangements.length; } /** * @notice Get information about staker's fee rate * @param _node Address of staker * @param _period Period to get fee delta */ function getNodeFeeDelta(address _node, uint16 _period) // TODO "virtual" only for tests, probably will be removed after #1512 public view virtual returns (int256) { // TODO remove after upgrade #2579 if (_node == RESERVED_NODE && _period == 11) { return 55; } return nodes[_node].feeDelta[_period]; } /** * @notice Return the information about arrangement */ function getArrangementInfo(bytes16 _policyId, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (ArrangementInfo) external view returns (address node, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { ArrangementInfo storage info = policies[_policyId].arrangements[_index]; node = info.node; indexOfDowntimePeriods = info.indexOfDowntimePeriods; lastRefundedPeriod = info.lastRefundedPeriod; } /** * @dev Get Policy structure by delegatecall */ function delegateGetPolicy(address _target, bytes16 _policyId) internal returns (Policy memory result) { bytes32 memoryAddress = delegateGetData(_target, this.policies.selector, 1, bytes32(_policyId), 0); assembly { result := memoryAddress } } /** * @dev Get ArrangementInfo structure by delegatecall */ function delegateGetArrangementInfo(address _target, bytes16 _policyId, uint256 _index) internal returns (ArrangementInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getArrangementInfo.selector, 2, bytes32(_policyId), bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get NodeInfo structure by delegatecall */ function delegateGetNodeInfo(address _target, address _node) internal returns (MemoryNodeInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.nodes.selector, 1, bytes32(uint256(_node)), 0); assembly { result := memoryAddress } } /** * @dev Get feeRateRange structure by delegatecall */ function delegateGetFeeRateRange(address _target) internal returns (Range memory result) { bytes32 memoryAddress = delegateGetData(_target, this.feeRateRange.selector, 0, 0, 0); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint64(delegateGet(_testTarget, this.resetTimestamp.selector)) == resetTimestamp); Range memory rangeToCheck = delegateGetFeeRateRange(_testTarget); require(feeRateRange.min == rangeToCheck.min && feeRateRange.defaultValue == rangeToCheck.defaultValue && feeRateRange.max == rangeToCheck.max); Policy storage policy = policies[RESERVED_POLICY_ID]; Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID); require(policyToCheck.sponsor == policy.sponsor && policyToCheck.owner == policy.owner && policyToCheck.feeRate == policy.feeRate && policyToCheck.startTimestamp == policy.startTimestamp && policyToCheck.endTimestamp == policy.endTimestamp && policyToCheck.disabled == policy.disabled); require(delegateGet(_testTarget, this.getArrangementsLength.selector, RESERVED_POLICY_ID) == policy.arrangements.length); if (policy.arrangements.length > 0) { ArrangementInfo storage arrangement = policy.arrangements[0]; ArrangementInfo memory arrangementToCheck = delegateGetArrangementInfo( _testTarget, RESERVED_POLICY_ID, 0); require(arrangementToCheck.node == arrangement.node && arrangementToCheck.indexOfDowntimePeriods == arrangement.indexOfDowntimePeriods && arrangementToCheck.lastRefundedPeriod == arrangement.lastRefundedPeriod); } NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; MemoryNodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE); require(nodeInfoToCheck.fee == nodeInfo.fee && nodeInfoToCheck.feeRate == nodeInfo.feeRate && nodeInfoToCheck.previousFeePeriod == nodeInfo.previousFeePeriod && nodeInfoToCheck.minFeeRate == nodeInfo.minFeeRate); require(int256(delegateGet(_testTarget, this.getNodeFeeDelta.selector, bytes32(bytes20(RESERVED_NODE)), bytes32(uint256(11)))) == getNodeFeeDelta(RESERVED_NODE, 11)); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); if (resetTimestamp == 0) { resetTimestamp = uint64(block.timestamp); } // Create fake Policy and NodeInfo to use them in verifyState(address) Policy storage policy = policies[RESERVED_POLICY_ID]; policy.sponsor = msg.sender; policy.owner = address(this); policy.startTimestamp = 1; policy.endTimestamp = 2; policy.feeRate = 3; policy.disabled = true; policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22)); NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; nodeInfo.fee = 100; nodeInfo.feeRate = 33; nodeInfo.previousFeePeriod = 44; nodeInfo.feeDelta[11] = 55; nodeInfo.minFeeRate = 777; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _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"); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./Upgradeable.sol"; import "../../zeppelin/utils/Address.sol"; /** * @notice ERC897 - ERC DelegateProxy */ interface ERCProxy { function proxyType() external pure returns (uint256); function implementation() external view returns (address); } /** * @notice Proxying requests to other contracts. * Client should use ABI of real contract and address of this contract */ contract Dispatcher is Upgradeable, ERCProxy { using Address for address; event Upgraded(address indexed from, address indexed to, address owner); event RolledBack(address indexed from, address indexed to, address owner); /** * @dev Set upgrading status before and after operations */ modifier upgrading() { isUpgrade = UPGRADE_TRUE; _; isUpgrade = UPGRADE_FALSE; } /** * @param _target Target contract address */ constructor(address _target) upgrading { require(_target.isContract()); // Checks that target contract inherits Dispatcher state verifyState(_target); // `verifyState` must work with its contract verifyUpgradeableState(_target, _target); target = _target; finishUpgrade(); emit Upgraded(address(0), _target, msg.sender); } //------------------------ERC897------------------------ /** * @notice ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() external pure override returns (uint256) { return 2; } /** * @notice ERC897, gets the address of the implementation where every call will be delegated */ function implementation() external view override returns (address) { return target; } //------------------------------------------------------------ /** * @notice Verify new contract storage and upgrade target * @param _target New target contract address */ function upgrade(address _target) public onlyOwner upgrading { require(_target.isContract()); // Checks that target contract has "correct" (as much as possible) state layout verifyState(_target); //`verifyState` must work with its contract verifyUpgradeableState(_target, _target); if (target.isContract()) { verifyUpgradeableState(target, _target); } previousTarget = target; target = _target; finishUpgrade(); emit Upgraded(previousTarget, _target, msg.sender); } /** * @notice Rollback to previous target * @dev Test storage carefully before upgrade again after rollback */ function rollback() public onlyOwner upgrading { require(previousTarget.isContract()); emit RolledBack(target, previousTarget, msg.sender); // should be always true because layout previousTarget -> target was already checked // but `verifyState` is not 100% accurate so check again verifyState(previousTarget); if (target.isContract()) { verifyUpgradeableState(previousTarget, target); } target = previousTarget; previousTarget = address(0); finishUpgrade(); } /** * @dev Call verifyState method for Upgradeable contract */ function verifyUpgradeableState(address _from, address _to) private { (bool callSuccess,) = _from.delegatecall(abi.encodeWithSelector(this.verifyState.selector, _to)); require(callSuccess); } /** * @dev Call finishUpgrade method from the Upgradeable contract */ function finishUpgrade() private { (bool callSuccess,) = target.delegatecall(abi.encodeWithSelector(this.finishUpgrade.selector, target)); require(callSuccess); } function verifyState(address _testTarget) public override onlyWhileUpgrading { //checks equivalence accessing state through new contract and current storage require(address(uint160(delegateGet(_testTarget, this.owner.selector))) == owner()); require(address(uint160(delegateGet(_testTarget, this.target.selector))) == target); require(address(uint160(delegateGet(_testTarget, this.previousTarget.selector))) == previousTarget); require(uint8(delegateGet(_testTarget, this.isUpgrade.selector)) == isUpgrade); } /** * @dev Override function using empty code because no reason to call this function in Dispatcher */ function finishUpgrade(address) public override {} /** * @dev Receive function sends empty request to the target contract */ receive() external payable { assert(target.isContract()); // execute receive function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(""); if (!callSuccess) { revert(); } } /** * @dev Fallback function sends all requests to the target contract */ fallback() external payable { assert(target.isContract()); // execute requested function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/utils/Address.sol"; import "../../zeppelin/token/ERC20/SafeERC20.sol"; import "./StakingInterface.sol"; import "../../zeppelin/proxy/Initializable.sol"; /** * @notice Router for accessing interface contract */ contract StakingInterfaceRouter is Ownable { BaseStakingInterface public target; /** * @param _target Address of the interface contract */ constructor(BaseStakingInterface _target) { require(address(_target.token()) != address(0)); target = _target; } /** * @notice Upgrade interface * @param _target New contract address */ function upgrade(BaseStakingInterface _target) external onlyOwner { require(address(_target.token()) != address(0)); target = _target; } } /** * @notice Internal base class for AbstractStakingContract and InitializableStakingContract */ abstract contract RawStakingContract { using Address for address; /** * @dev Returns address of StakingInterfaceRouter */ function router() public view virtual returns (StakingInterfaceRouter); /** * @dev Checks permission for calling fallback function */ function isFallbackAllowed() public virtual returns (bool); /** * @dev Withdraw tokens from staking contract */ function withdrawTokens(uint256 _value) public virtual; /** * @dev Withdraw ETH from staking contract */ function withdrawETH() public virtual; receive() external payable {} /** * @dev Function sends all requests to the target contract */ fallback() external payable { require(isFallbackAllowed()); address target = address(router().target()); require(target.isContract()); // execute requested function from target contract (bool callSuccess, ) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } /** * @notice Base class for any staking contract (not usable with openzeppelin proxy) * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract AbstractStakingContract is RawStakingContract { StakingInterfaceRouter immutable router_; NuCypherToken public immutable token; /** * @param _router Interface router contract address */ constructor(StakingInterfaceRouter _router) { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } /** * @notice Base class for any staking contract usable with openzeppelin proxy * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract InitializableStakingContract is Initializable, RawStakingContract { StakingInterfaceRouter router_; NuCypherToken public token; /** * @param _router Interface router contract address */ function initialize(StakingInterfaceRouter _router) public initializer { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./AbstractStakingContract.sol"; import "../NuCypherToken.sol"; import "../StakingEscrow.sol"; import "../PolicyManager.sol"; import "../WorkLock.sol"; /** * @notice Base StakingInterface */ contract BaseStakingInterface { address public immutable stakingInterfaceAddress; NuCypherToken public immutable token; StakingEscrow public immutable escrow; PolicyManager public immutable policyManager; WorkLock public immutable workLock; /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) { require(_token.totalSupply() > 0 && _escrow.secondsPerPeriod() > 0 && _policyManager.secondsPerPeriod() > 0 && // in case there is no worklock contract (address(_workLock) == address(0) || _workLock.boostingRefund() > 0)); token = _token; escrow = _escrow; policyManager = _policyManager; workLock = _workLock; stakingInterfaceAddress = address(this); } /** * @dev Checks executing through delegate call */ modifier onlyDelegateCall() { require(stakingInterfaceAddress != address(this)); _; } /** * @dev Checks the existence of the worklock contract */ modifier workLockSet() { require(address(workLock) != address(0)); _; } } /** * @notice Interface for accessing main contracts from a staking contract * @dev All methods must be stateless because this code will be executed by delegatecall call, use immutable fields. * @dev |v1.7.1| */ contract StakingInterface is BaseStakingInterface { event DepositedAsStaker(address indexed sender, uint256 value, uint16 periods); event WithdrawnAsStaker(address indexed sender, uint256 value); event DepositedAndIncreased(address indexed sender, uint256 index, uint256 value); event LockedAndCreated(address indexed sender, uint256 value, uint16 periods); event LockedAndIncreased(address indexed sender, uint256 index, uint256 value); event Divided(address indexed sender, uint256 index, uint256 newValue, uint16 periods); event Merged(address indexed sender, uint256 index1, uint256 index2); event Minted(address indexed sender); event PolicyFeeWithdrawn(address indexed sender, uint256 value); event MinFeeRateSet(address indexed sender, uint256 value); event ReStakeSet(address indexed sender, bool reStake); event WorkerBonded(address indexed sender, address worker); event Prolonged(address indexed sender, uint256 index, uint16 periods); event WindDownSet(address indexed sender, bool windDown); event SnapshotSet(address indexed sender, bool snapshotsEnabled); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); event BidCanceled(address indexed sender); event CompensationWithdrawn(address indexed sender); /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) BaseStakingInterface(_token, _escrow, _policyManager, _workLock) { } /** * @notice Bond worker in the staking escrow * @param _worker Worker address */ function bondWorker(address _worker) public onlyDelegateCall { escrow.bondWorker(_worker); emit WorkerBonded(msg.sender, _worker); } /** * @notice Set `reStake` parameter in the staking escrow * @param _reStake Value for parameter */ function setReStake(bool _reStake) public onlyDelegateCall { escrow.setReStake(_reStake); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens to the staking escrow * @param _value Amount of token to deposit * @param _periods Amount of periods during which tokens will be locked */ function depositAsStaker(uint256 _value, uint16 _periods) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.deposit(address(this), _value, _periods); emit DepositedAsStaker(msg.sender, _value, _periods); } /** * @notice Deposit tokens to the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.depositAndIncrease(_index, _value); emit DepositedAndIncreased(msg.sender, _index, _value); } /** * @notice Withdraw available amount of tokens from the staking escrow to the staking contract * @param _value Amount of token to withdraw */ function withdrawAsStaker(uint256 _value) public onlyDelegateCall { escrow.withdraw(_value); emit WithdrawnAsStaker(msg.sender, _value); } /** * @notice Lock some tokens in the staking escrow * @param _value Amount of tokens which should lock * @param _periods Amount of periods during which tokens will be locked */ function lockAndCreate(uint256 _value, uint16 _periods) public onlyDelegateCall { escrow.lockAndCreate(_value, _periods); emit LockedAndCreated(msg.sender, _value, _periods); } /** * @notice Lock some tokens in the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { escrow.lockAndIncrease(_index, _value); emit LockedAndIncreased(msg.sender, _index, _value); } /** * @notice Divide stake into two parts * @param _index Index of stake * @param _newValue New stake value * @param _periods Amount of periods for extending stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) public onlyDelegateCall { escrow.divideStake(_index, _newValue, _periods); emit Divided(msg.sender, _index, _newValue, _periods); } /** * @notice Merge two sub-stakes into one * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) public onlyDelegateCall { escrow.mergeStake(_index1, _index2); emit Merged(msg.sender, _index1, _index2); } /** * @notice Mint tokens in the staking escrow */ function mint() public onlyDelegateCall { escrow.mint(); emit Minted(msg.sender); } /** * @notice Withdraw available policy fees from the policy manager to the staking contract */ function withdrawPolicyFee() public onlyDelegateCall { uint256 value = policyManager.withdraw(); emit PolicyFeeWithdrawn(msg.sender, value); } /** * @notice Set the minimum fee that the staker will accept in the policy manager contract */ function setMinFeeRate(uint256 _minFeeRate) public onlyDelegateCall { policyManager.setMinFeeRate(_minFeeRate); emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _periods Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _periods) public onlyDelegateCall { escrow.prolongStake(_index, _periods); emit Prolonged(msg.sender, _index, _periods); } /** * @notice Set `windDown` parameter in the staking escrow * @param _windDown Value for parameter */ function setWindDown(bool _windDown) public onlyDelegateCall { escrow.setWindDown(_windDown); emit WindDownSet(msg.sender, _windDown); } /** * @notice Set `snapshots` parameter in the staking escrow * @param _enableSnapshots Value for parameter */ function setSnapshots(bool _enableSnapshots) public onlyDelegateCall { escrow.setSnapshots(_enableSnapshots); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Bid for tokens by transferring ETH */ function bid(uint256 _value) public payable onlyDelegateCall workLockSet { workLock.bid{value: _value}(); emit Bid(msg.sender, _value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() public onlyDelegateCall workLockSet { workLock.cancelBid(); emit BidCanceled(msg.sender); } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() public onlyDelegateCall workLockSet { workLock.withdrawCompensation(); emit CompensationWithdrawn(msg.sender); } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract */ function claim() public onlyDelegateCall workLockSet { uint256 claimedTokens = workLock.claim(); emit Claimed(msg.sender, claimedTokens); } /** * @notice Refund ETH for the completed work */ function refund() public onlyDelegateCall workLockSet { uint256 refundETH = workLock.refund(); emit Refund(msg.sender, refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/utils/Address.sol"; import "../zeppelin/ownership/Ownable.sol"; import "./NuCypherToken.sol"; import "./StakingEscrow.sol"; import "./lib/AdditionalMath.sol"; /** * @notice The WorkLock distribution contract */ contract WorkLock is Ownable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using Address for address payable; using Address for address; event Deposited(address indexed sender, uint256 value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH, uint256 completedWork); event Canceled(address indexed sender, uint256 value); event BiddersChecked(address indexed sender, uint256 startIndex, uint256 endIndex); event ForceRefund(address indexed sender, address indexed bidder, uint256 refundETH); event CompensationWithdrawn(address indexed sender, uint256 value); event Shutdown(address indexed sender); struct WorkInfo { uint256 depositedETH; uint256 completedWork; bool claimed; uint128 index; } uint16 public constant SLOWING_REFUND = 100; uint256 private constant MAX_ETH_SUPPLY = 2e10 ether; NuCypherToken public immutable token; StakingEscrow public immutable escrow; /* * @dev WorkLock calculations: * bid = minBid + bonusETHPart * bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens * bonusDepositRate = bonusTokenSupply / bonusETHSupply * claimedTokens = minAllowableLockedTokens + bonusETHPart * bonusDepositRate * bonusRefundRate = bonusDepositRate * SLOWING_REFUND / boostingRefund * refundETH = completedWork / refundRate */ uint256 public immutable boostingRefund; uint256 public immutable minAllowedBid; uint16 public immutable stakingPeriods; // copy from the escrow contract uint256 public immutable maxAllowableLockedTokens; uint256 public immutable minAllowableLockedTokens; uint256 public tokenSupply; uint256 public startBidDate; uint256 public endBidDate; uint256 public endCancellationDate; uint256 public bonusETHSupply; mapping(address => WorkInfo) public workInfo; mapping(address => uint256) public compensation; address[] public bidders; // if value == bidders.length then WorkLock is fully checked uint256 public nextBidderToCheck; /** * @dev Checks timestamp regarding cancellation window */ modifier afterCancellationWindow() { require(block.timestamp >= endCancellationDate, "Operation is allowed when cancellation phase is over"); _; } /** * @param _token Token contract * @param _escrow Escrow contract * @param _startBidDate Timestamp when bidding starts * @param _endBidDate Timestamp when bidding will end * @param _endCancellationDate Timestamp when cancellation will ends * @param _boostingRefund Coefficient to boost refund ETH * @param _stakingPeriods Amount of periods during which tokens will be locked after claiming * @param _minAllowedBid Minimum allowed ETH amount for bidding */ constructor( NuCypherToken _token, StakingEscrow _escrow, uint256 _startBidDate, uint256 _endBidDate, uint256 _endCancellationDate, uint256 _boostingRefund, uint16 _stakingPeriods, uint256 _minAllowedBid ) { uint256 totalSupply = _token.totalSupply(); require(totalSupply > 0 && // token contract is deployed and accessible _escrow.secondsPerPeriod() > 0 && // escrow contract is deployed and accessible _escrow.token() == _token && // same token address for worklock and escrow _endBidDate > _startBidDate && // bidding period lasts some time _endBidDate > block.timestamp && // there is time to make a bid _endCancellationDate >= _endBidDate && // cancellation window includes bidding _minAllowedBid > 0 && // min allowed bid was set _boostingRefund > 0 && // boosting coefficient was set _stakingPeriods >= _escrow.minLockedPeriods()); // staking duration is consistent with escrow contract // worst case for `ethToWork()` and `workToETH()`, // when ethSupply == MAX_ETH_SUPPLY and tokenSupply == totalSupply require(MAX_ETH_SUPPLY * totalSupply * SLOWING_REFUND / MAX_ETH_SUPPLY / totalSupply == SLOWING_REFUND && MAX_ETH_SUPPLY * totalSupply * _boostingRefund / MAX_ETH_SUPPLY / totalSupply == _boostingRefund); token = _token; escrow = _escrow; startBidDate = _startBidDate; endBidDate = _endBidDate; endCancellationDate = _endCancellationDate; boostingRefund = _boostingRefund; stakingPeriods = _stakingPeriods; minAllowedBid = _minAllowedBid; maxAllowableLockedTokens = _escrow.maxAllowableLockedTokens(); minAllowableLockedTokens = _escrow.minAllowableLockedTokens(); } /** * @notice Deposit tokens to contract * @param _value Amount of tokens to transfer */ function tokenDeposit(uint256 _value) external { require(block.timestamp < endBidDate, "Can't deposit more tokens after end of bidding"); token.safeTransferFrom(msg.sender, address(this), _value); tokenSupply += _value; emit Deposited(msg.sender, _value); } /** * @notice Calculate amount of tokens that will be get for specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToTokens(uint256 _ethAmount) public view returns (uint256) { if (_ethAmount < minAllowedBid) { return 0; } // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return tokenSupply / bidders.length; } uint256 bonusETH = _ethAmount - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; return minAllowableLockedTokens + bonusETH.mul(bonusTokenSupply).div(bonusETHSupply); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH */ function ethToWork(uint256 _ethAmount, uint256 _tokenSupply, uint256 _ethSupply) internal view returns (uint256) { return _ethAmount.mul(_tokenSupply).mul(SLOWING_REFUND).divCeil(_ethSupply.mul(boostingRefund)); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding * @param _ethToReclaim Specified sum of ETH staker wishes to reclaim following completion of work * @param _restOfDepositedETH Remaining ETH in staker's deposit once ethToReclaim sum has been subtracted * @dev _ethToReclaim + _restOfDepositedETH = depositedETH */ function ethToWork(uint256 _ethToReclaim, uint256 _restOfDepositedETH) internal view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return ethToWork(_ethToReclaim, tokenSupply, baseETHSupply); } uint256 baseETH = 0; uint256 bonusETH = 0; // If the staker's total remaining deposit (including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then only the base part is used to calculate the work required to reclaim ETH if (_ethToReclaim + _restOfDepositedETH <= minAllowedBid) { baseETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is still greater than the minimum bid size, // then only the bonus part is used to calculate the work required to reclaim ETH } else if (_restOfDepositedETH >= minAllowedBid) { bonusETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then both the base and bonus parts must be used to calculate the work required to reclaim ETH } else { bonusETH = _ethToReclaim + _restOfDepositedETH - minAllowedBid; baseETH = _ethToReclaim - bonusETH; } uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; uint256 work = 0; if (baseETH > 0) { work = ethToWork(baseETH, baseTokenSupply, baseETHSupply); } if (bonusETH > 0) { uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; work += ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); } return work; } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToWork(uint256 _ethAmount) public view returns (uint256) { return ethToWork(_ethAmount, 0); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work */ function workToETH(uint256 _completedWork, uint256 _ethSupply, uint256 _tokenSupply) internal view returns (uint256) { return _completedWork.mul(_ethSupply).mul(boostingRefund).div(_tokenSupply.mul(SLOWING_REFUND)); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work * @dev This value will be fixed only after end of bidding */ function workToETH(uint256 _completedWork, uint256 _depositedETH) public view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return workToETH(_completedWork, baseETHSupply, tokenSupply); } uint256 bonusWork = 0; uint256 bonusETH = 0; uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; if (_depositedETH > minAllowedBid) { bonusETH = _depositedETH - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; bonusWork = ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); if (_completedWork <= bonusWork) { return workToETH(_completedWork, bonusETHSupply, bonusTokenSupply); } } _completedWork -= bonusWork; return bonusETH + workToETH(_completedWork, baseETHSupply, baseTokenSupply); } /** * @notice Get remaining work to full refund */ function getRemainingWork(address _bidder) external view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; uint256 completedWork = escrow.getCompletedWork(_bidder).sub(info.completedWork); uint256 remainingWork = ethToWork(info.depositedETH); if (remainingWork <= completedWork) { return 0; } return remainingWork - completedWork; } /** * @notice Get length of bidders array */ function getBiddersLength() external view returns (uint256) { return bidders.length; } /** * @notice Bid for tokens by transferring ETH */ function bid() external payable { require(block.timestamp >= startBidDate, "Bidding is not open yet"); require(block.timestamp < endBidDate, "Bidding is already finished"); WorkInfo storage info = workInfo[msg.sender]; // first bid if (info.depositedETH == 0) { require(msg.value >= minAllowedBid, "Bid must be at least minimum"); require(bidders.length < tokenSupply / minAllowableLockedTokens, "Not enough tokens for more bidders"); info.index = uint128(bidders.length); bidders.push(msg.sender); bonusETHSupply = bonusETHSupply.add(msg.value - minAllowedBid); } else { bonusETHSupply = bonusETHSupply.add(msg.value); } info.depositedETH = info.depositedETH.add(msg.value); emit Bid(msg.sender, msg.value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() external { require(block.timestamp < endCancellationDate, "Cancellation allowed only during cancellation window"); WorkInfo storage info = workInfo[msg.sender]; require(info.depositedETH > 0, "No bid to cancel"); require(!info.claimed, "Tokens are already claimed"); uint256 refundETH = info.depositedETH; info.depositedETH = 0; // remove from bidders array, move last bidder to the empty place uint256 lastIndex = bidders.length - 1; if (info.index != lastIndex) { address lastBidder = bidders[lastIndex]; bidders[info.index] = lastBidder; workInfo[lastBidder].index = info.index; } bidders.pop(); if (refundETH > minAllowedBid) { bonusETHSupply = bonusETHSupply.sub(refundETH - minAllowedBid); } msg.sender.sendValue(refundETH); emit Canceled(msg.sender, refundETH); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function shutdown() external onlyOwner { require(!isClaimingAvailable(), "Claiming has already been enabled"); internalShutdown(); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function internalShutdown() internal { startBidDate = 0; endBidDate = 0; endCancellationDate = uint256(0) - 1; // "infinite" cancellation window token.safeTransfer(owner(), tokenSupply); emit Shutdown(msg.sender); } /** * @notice Make force refund to bidders who can get tokens more than maximum allowed * @param _biddersForRefund Sorted list of unique bidders. Only bidders who must receive a refund */ function forceRefund(address payable[] calldata _biddersForRefund) external afterCancellationWindow { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); uint256 length = _biddersForRefund.length; require(length > 0, "Must be at least one bidder for a refund"); uint256 minNumberOfBidders = tokenSupply.divCeil(maxAllowableLockedTokens); if (bidders.length < minNumberOfBidders) { internalShutdown(); return; } address previousBidder = _biddersForRefund[0]; uint256 minBid = workInfo[previousBidder].depositedETH; uint256 maxBid = minBid; // get minimum and maximum bids for (uint256 i = 1; i < length; i++) { address bidder = _biddersForRefund[i]; uint256 depositedETH = workInfo[bidder].depositedETH; require(bidder > previousBidder && depositedETH > 0, "Addresses must be an array of unique bidders"); if (minBid > depositedETH) { minBid = depositedETH; } else if (maxBid < depositedETH) { maxBid = depositedETH; } previousBidder = bidder; } uint256[] memory refunds = new uint256[](length); // first step - align at a minimum bid if (minBid != maxBid) { for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; if (info.depositedETH > minBid) { refunds[i] = info.depositedETH - minBid; info.depositedETH = minBid; bonusETHSupply -= refunds[i]; } } } require(ethToTokens(minBid) > maxAllowableLockedTokens, "At least one of bidders has allowable bid"); // final bids adjustment (only for bonus part) // (min_whale_bid * token_supply - max_stake * eth_supply) / (token_supply - max_stake * n_whales) uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 minBonusETH = minBid - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 refundETH = minBonusETH.mul(bonusTokenSupply) .sub(maxBonusTokens.mul(bonusETHSupply)) .divCeil(bonusTokenSupply - maxBonusTokens.mul(length)); uint256 resultBid = minBid.sub(refundETH); bonusETHSupply -= length * refundETH; for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; refunds[i] += refundETH; info.depositedETH = resultBid; } // reset verification nextBidderToCheck = 0; // save a refund for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; compensation[bidder] += refunds[i]; emit ForceRefund(msg.sender, bidder, refunds[i]); } } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() external { uint256 refund = compensation[msg.sender]; require(refund > 0, "There is no compensation"); compensation[msg.sender] = 0; msg.sender.sendValue(refund); emit CompensationWithdrawn(msg.sender, refund); } /** * @notice Check that the claimed tokens are within `maxAllowableLockedTokens` for all participants, * starting from the last point `nextBidderToCheck` * @dev Method stops working when the remaining gas is less than `_gasToSaveState` * and saves the state in `nextBidderToCheck`. * If all bidders have been checked then `nextBidderToCheck` will be equal to the length of the bidders array */ function verifyBiddingCorrectness(uint256 _gasToSaveState) external afterCancellationWindow returns (uint256) { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); // all participants bid with the same minimum amount of eth uint256 index = nextBidderToCheck; if (bonusETHSupply == 0) { require(tokenSupply / bidders.length <= maxAllowableLockedTokens, "Not enough bidders"); index = bidders.length; } uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 maxBidFromMaxStake = minAllowedBid + maxBonusTokens.mul(bonusETHSupply).div(bonusTokenSupply); while (index < bidders.length && gasleft() > _gasToSaveState) { address bidder = bidders[index]; require(workInfo[bidder].depositedETH <= maxBidFromMaxStake, "Bid is greater than max allowable bid"); index++; } if (index != nextBidderToCheck) { emit BiddersChecked(msg.sender, nextBidderToCheck, index); nextBidderToCheck = index; } return nextBidderToCheck; } /** * @notice Checks if claiming available */ function isClaimingAvailable() public view returns (bool) { return block.timestamp >= endCancellationDate && nextBidderToCheck == bidders.length; } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract. */ function claim() external returns (uint256 claimedTokens) { require(isClaimingAvailable(), "Claiming has not been enabled yet"); WorkInfo storage info = workInfo[msg.sender]; require(!info.claimed, "Tokens are already claimed"); claimedTokens = ethToTokens(info.depositedETH); require(claimedTokens > 0, "Nothing to claim"); info.claimed = true; token.approve(address(escrow), claimedTokens); escrow.depositFromWorkLock(msg.sender, claimedTokens, stakingPeriods); info.completedWork = escrow.setWorkMeasurement(msg.sender, true); emit Claimed(msg.sender, claimedTokens); } /** * @notice Get available refund for bidder */ function getAvailableRefund(address _bidder) public view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; // nothing to refund if (info.depositedETH == 0) { return 0; } uint256 currentWork = escrow.getCompletedWork(_bidder); uint256 completedWork = currentWork.sub(info.completedWork); // no work that has been completed since last refund if (completedWork == 0) { return 0; } uint256 refundETH = workToETH(completedWork, info.depositedETH); if (refundETH > info.depositedETH) { refundETH = info.depositedETH; } return refundETH; } /** * @notice Refund ETH for the completed work */ function refund() external returns (uint256 refundETH) { WorkInfo storage info = workInfo[msg.sender]; require(info.claimed, "Tokens must be claimed before refund"); refundETH = getAvailableRefund(msg.sender); require(refundETH > 0, "Nothing to refund: there is no ETH to refund or no completed work"); if (refundETH == info.depositedETH) { escrow.setWorkMeasurement(msg.sender, false); } info.depositedETH = info.depositedETH.sub(refundETH); // convert refund back to work to eliminate potential rounding errors uint256 completedWork = ethToWork(refundETH, info.depositedETH); info.completedWork = info.completedWork.add(completedWork); emit Refund(msg.sender, refundETH, completedWork); msg.sender.sendValue(refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner **/ contract PoolingStakingContract is AbstractStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited(address indexed sender, uint256 value, uint256 depositedTokens); event TokensWithdrawn(address indexed sender, uint256 value, uint256 depositedTokens); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } StakingEscrow public immutable escrow; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public ownerFraction; uint256 public ownerWithdrawnReward; uint256 public ownerWithdrawnETH; mapping (address => Delegator) public delegators; bool depositIsEnabled = true; /** * @param _router Address of the StakingInterfaceRouter contract * @param _ownerFraction Base owner's portion of reward */ constructor( StakingInterfaceRouter _router, uint256 _ownerFraction ) AbstractStakingContract(_router) { escrow = _router.target().escrow(); ownerFraction = _ownerFraction; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens += _value; token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens + freeTokens - totalDepositedTokens; if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for pool owner */ function getAvailableOwnerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { maxAllowableReward = reward.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); } else { maxAllowableReward = reward; } return maxAllowableReward.sub(ownerWithdrawnReward); } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableReward = reward.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to owner */ function withdrawOwnerReward() public onlyOwner { uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableOwnerReward(); if (availableReward > balance) { availableReward = balance; } require(availableReward > 0, "There is no available reward to withdraw"); ownerWithdrawnReward = ownerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw amount of tokens to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); uint256 availableReward = getAvailableReward(msg.sender); Delegator storage delegator = delegators[msg.sender]; require(_value <= availableReward + delegator.depositedTokens, "Requested amount of tokens exceeded allowed portion"); if (_value <= availableReward) { delegator.withdrawnReward += _value; totalWithdrawnReward += _value; } else { delegator.withdrawnReward = delegator.withdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); uint256 depositToWithdraw = _value - availableReward; uint256 newDepositedTokens = delegator.depositedTokens - depositToWithdraw; uint256 newWithdrawnReward = delegator.withdrawnReward.mul(newDepositedTokens).div(delegator.depositedTokens); uint256 newWithdrawnETH = delegator.withdrawnETH.mul(newDepositedTokens).div(delegator.depositedTokens); totalDepositedTokens -= depositToWithdraw; totalWithdrawnReward -= (delegator.withdrawnReward - newWithdrawnReward); totalWithdrawnETH -= (delegator.withdrawnETH - newWithdrawnETH); delegator.depositedTokens = newDepositedTokens; delegator.withdrawnReward = newWithdrawnReward; delegator.withdrawnETH = newWithdrawnETH; } token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available ether for owner */ function getAvailableOwnerETH() public view returns (uint256) { // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(ownerWithdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to pool owner */ function withdrawOwnerETH() public onlyOwner { uint256 availableETH = getAvailableOwnerETH(); require(availableETH > 0, "There is no available ETH to withdraw"); ownerWithdrawnETH = ownerWithdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner **/ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers **/ contract PoolingStakingContractV2 is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event WorkerOwnerSet(address indexed sender, address indexed workerOwner); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } /** * Defines base fraction and precision of worker fraction. * E.g., for a value of 10000, a worker fraction of 100 represents 1% of reward (100/10000) */ uint256 public constant BASIS_FRACTION = 10000; StakingEscrow public escrow; address public workerOwner; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION (10000), if _workerFraction = BASIS_FRACTION -> means 100% reward as commission. * For example, 100 worker fraction is 1% of reward * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) external initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workerFraction = _workerFraction; workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice withdrawAll() is allowed */ function isWithdrawAllAllowed() public view returns (bool) { // no tokens in StakingEscrow contract which belong to pool return escrow.getAllTokens(address(this)) == 0; } /** * @notice deposit() is allowed */ function isDepositAllowed() public view returns (bool) { // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // no sub-stakes and no earned reward return isWithdrawAllAllowed() && freeTokens == totalDepositedTokens; } /** * @notice Set worker owner address */ function setWorkerOwner(address _workerOwner) external onlyOwner { workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice Calculate worker's fraction depending on deposited tokens * Override to implement dynamic worker fraction. */ function getWorkerFraction() public view virtual returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(isDepositAllowed(), "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { // locked + unlocked tokens in StakingEscrow contract which belong to pool uint256 stakedTokens = escrow.getAllTokens(address(this)); // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // tokens in excess of the initially deposited uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); // check how many of reward tokens belong directly to pool if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward. * Available and withdrawn reward together to use in delegator/owner reward calculations */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { // total current and historical reward uint256 reward = getCumulativeReward(); // calculate total reward for worker including historical reward uint256 maxAllowableReward; // usual case if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); // special case when there are no delegators } else { maxAllowableReward = reward; } // check that worker has any new reward if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableDelegatorReward(address _delegator) public view returns (uint256) { // special case when there are no delegators if (totalDepositedTokens == 0) { return 0; } // total current and historical reward uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); // calculate total reward for delegator including historical reward // excluding worker share uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); // check that worker has any new reward if (maxAllowableReward > delegator.withdrawnReward) { return maxAllowableReward - delegator.withdrawnReward; } return 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { require(isWithdrawAllAllowed(), "Withdraw deposit and reward must be enabled"); uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading: availableReward and availableWorkerReward use same calls to external contracts uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableDelegatorETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableDelegatorETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; uint256 availableETH = getAvailableDelegatorETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract holds tokens for vesting. * Also tokens can be used as a stake in the staking escrow contract */ contract PreallocationEscrow is AbstractStakingContract, Ownable { using SafeMath for uint256; using SafeERC20 for NuCypherToken; using Address for address payable; event TokensDeposited(address indexed sender, uint256 value, uint256 duration); event TokensWithdrawn(address indexed owner, uint256 value); event ETHWithdrawn(address indexed owner, uint256 value); StakingEscrow public immutable stakingEscrow; uint256 public lockedValue; uint256 public endLockTimestamp; /** * @param _router Address of the StakingInterfaceRouter contract */ constructor(StakingInterfaceRouter _router) AbstractStakingContract(_router) { stakingEscrow = _router.target().escrow(); } /** * @notice Initial tokens deposit * @param _sender Token sender * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(address _sender, uint256 _value, uint256 _duration) internal { require(lockedValue == 0 && _value > 0); endLockTimestamp = block.timestamp.add(_duration); lockedValue = _value; token.safeTransferFrom(_sender, address(this), _value); emit TokensDeposited(_sender, _value, _duration); } /** * @notice Initial tokens deposit * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(uint256 _value, uint256 _duration) external { initialDeposit(msg.sender, _value, _duration); } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Initial tokens deposit * @param _from Sender * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of seconds during which tokens will be locked */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); initialDeposit(_from, _value, payload); } /** * @notice Get locked tokens value */ function getLockedTokens() public view returns (uint256) { if (endLockTimestamp <= block.timestamp) { return 0; } return lockedValue; } /** * @notice Withdraw available amount of tokens to owner * @param _value Amount of token to withdraw */ function withdrawTokens(uint256 _value) public override onlyOwner { uint256 balance = token.balanceOf(address(this)); require(balance >= _value); // Withdrawal invariant for PreallocationEscrow: // After withdrawing, the sum of all escrowed tokens (either here or in StakingEscrow) must exceed the locked amount require(balance - _value + stakingEscrow.getAllTokens(address(this)) >= getLockedTokens()); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value); } /** * @notice Withdraw available ETH to the owner */ function withdrawETH() public override onlyOwner { uint256 balance = address(this).balance; require(balance != 0); msg.sender.sendValue(balance); emit ETHWithdrawn(msg.sender, balance); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner * @author @vzotova and @roma_k **/ contract WorkLockPoolingContract is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; uint256 depositedETHWorkLock; uint256 refundedETHWorkLock; bool claimedWorkLockTokens; } uint256 public constant BASIS_FRACTION = 100; StakingEscrow public escrow; WorkLock public workLock; address public workerOwner; uint256 public totalDepositedTokens; uint256 public workLockClaimedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public totalWorkLockETHReceived; uint256 public totalWorkLockETHRefunded; uint256 public totalWorkLockETHWithdrawn; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; bool depositIsEnabled = true; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION, if _workerFraction = BASIS_FRACTION -> means 100% reward as commission * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) public initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workLock = _router.target().workLock(); workerFraction = _workerFraction; workerOwner = _workerOwner; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Calculate worker's fraction depending on deposited tokens */ function getWorkerFraction() public view returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Delegator can transfer ETH directly to workLock */ function escrowETH() external payable { Delegator storage delegator = delegators[msg.sender]; delegator.depositedETHWorkLock = delegator.depositedETHWorkLock.add(msg.value); totalWorkLockETHReceived = totalWorkLockETHReceived.add(msg.value); workLock.bid{value: msg.value}(); emit Bid(msg.sender, msg.value); } /** * @dev Hide method from StakingInterface */ function bid(uint256) public payable { revert(); } /** * @dev Hide method from StakingInterface */ function withdrawCompensation() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function cancelBid() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function claim() public pure { revert(); } /** * @notice Claim tokens in WorkLock and save number of claimed tokens */ function claimTokensFromWorkLock() public { workLockClaimedTokens = workLock.claim(); totalDepositedTokens = totalDepositedTokens.add(workLockClaimedTokens); emit Claimed(address(this), workLockClaimedTokens); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount() external { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount(Delegator storage _delegator) internal { if (workLockClaimedTokens == 0 || _delegator.depositedETHWorkLock == 0 || _delegator.claimedWorkLockTokens) { return; } uint256 delegatorTokensShare = _delegator.depositedETHWorkLock.mul(workLockClaimedTokens) .div(totalWorkLockETHReceived); _delegator.depositedTokens = _delegator.depositedTokens.add(delegatorTokensShare); _delegator.claimedWorkLockTokens = true; emit Claimed(msg.sender, delegatorTokensShare); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); } else { maxAllowableReward = reward; } if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn - (refunded - refundWithdrawn) balance = balance.add(totalWithdrawnETH).add(totalWorkLockETHWithdrawn).sub(totalWorkLockETHRefunded); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw compensation and refund from WorkLock and save these numbers */ function refund() public { uint256 balance = address(this).balance; if (workLock.compensation(address(this)) > 0) { workLock.withdrawCompensation(); } workLock.refund(); uint256 refundETH = address(this).balance - balance; totalWorkLockETHRefunded = totalWorkLockETHRefunded.add(refundETH); emit Refund(address(this), refundETH); } /** * @notice Get available refund for delegator */ function getAvailableRefund(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableETH = totalWorkLockETHRefunded.mul(delegator.depositedETHWorkLock) .div(totalWorkLockETHReceived); uint256 availableETH = maxAllowableETH.sub(delegator.refundedETHWorkLock); uint256 balance = totalWorkLockETHRefunded.sub(totalWorkLockETHWithdrawn); if (availableETH > balance) { availableETH = balance; } return availableETH; } /* * @notice Withdraw available amount of ETH to delegator */ function withdrawRefund() external { uint256 availableETH = getAvailableRefund(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.refundedETHWorkLock = delegator.refundedETHWorkLock.add(availableETH); totalWorkLockETHWithdrawn = totalWorkLockETHWithdrawn.add(availableETH); msg.sender.sendValue(availableETH); emit Refund(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } }
Set the minimum acceptable fee rate (set by staker for their associated worker) Input value must fall within `feeRateRange` (global fee range)/
function setMinFeeRate(uint256 _minFeeRate) external { require(_minFeeRate >= feeRateRange.min && _minFeeRate <= feeRateRange.max, "The staker's min fee rate must fall within the global fee range"); NodeInfo storage nodeInfo = nodes[msg.sender]; if (nodeInfo.minFeeRate == _minFeeRate) { return; } nodeInfo.minFeeRate = _minFeeRate; emit MinFeeRateSet(msg.sender, _minFeeRate); }
1,393,337
./full_match/1/0xB09923cd48714286500300815F692052F8C5e293/sources/contracts/vaults/BaseVault.sol
@inheritdoc IVault/
function idleAssetsOf(address owner) public view virtual returns (uint256) { (, uint256 assets) = depositQueue.tryGet(owner); return assets; }
4,995,786
pragma solidity ^0.4.18; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } /* You should inherit from TokenBase. This implements ONLY the standard functions obeys ERC20, and NOTHING else. If you deploy this, you won&#39;t have anything useful. Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 .*/ contract ERC20 { /// 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) constant public 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) constant public returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract TokenBase is ERC20 { function transfer(address _to, uint256 _value) public returns (bool success) { // Prevent transfer to 0x0 address. require(_to != 0x0); // Check if the sender has enough require(balances[msg.sender] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); uint previousBalances = balances[msg.sender] + balances[_to]; balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[msg.sender] + balances[_to] == previousBalances); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { /// same as above require(_to != 0x0); require(balances[_from] >= _value); require(balances[_to] + _value > balances[_to]); uint previousBalances = balances[_from] + balances[_to]; balances[_from] -= _value; balances[_to] += _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); assert(balances[_from] + balances[_to] == previousBalances); return true; } function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; /// balance amount of tokens for address mapping (address => mapping (address => uint256)) allowed; } contract BAI20 is TokenBase { function () payable public { //if ether is sent to this address, send it back. //throw; require(false); } string public constant name = "BAI2.0"; string public constant symbol = "BAI"; uint256 private constant _INITIAL_SUPPLY = 21000000000; uint8 public decimals = 18; uint256 public totalSupply; string public version = "BAI2.0"; function BAI20( ) public { // init totalSupply = _INITIAL_SUPPLY * 10 ** 18; balances[msg.sender] = totalSupply; } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } }
Prevent transfer to 0x0 address. Check if the sender has enough Check for overflows Asserts are used to use static analysis to find bugs in your code. They should never fail
You should inherit from TokenBase. This implements ONLY the standard functions obeys ERC20, and NOTHING else. If you deploy this, you won&#39;t have anything useful. .*/ } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != 0x0); require(balances[msg.sender] >= _value); require(balances[_to] + _value > balances[_to]); uint previousBalances = balances[msg.sender] + balances[_to]; balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); assert(balances[msg.sender] + balances[_to] == previousBalances); return true; }
7,986,636
### Type of Solidity variable In solidity has three variable category - Fixed-size type - bool - uint - address - byte32 - Variable-size type - string - bytes - uint[] - mapping(uint => address) - User-define data - struct ``` struct User { unit id; address _address; } ``` - enum ``` enum User { ALICE, BOB } ``` ### Build-in Variable of Solidity - blockhash(uint blockNumber) returns (bytes32): hash of the given block - only works for 256 mostrecent, excluding current, blocks. - block.coinbase (address): current block miner’s address - block.difficulty (uint): current block difficulty - block.gaslimit (uint): current block gaslimit - block.number (uint): current block number - block.timestamp (uint): current block timestamp as seconds since unix epoch - gasleft() returns (uint256): remaining gas - msg.data (bytes): complete calldata - msg.gas (uint): remaining gas - deprecated in version 0.4.21 and to be replaced by gasleft() - msg.sender (address): sender of the message (current call) - msg.sig (bytes4): first four bytes of the calldata (i.e. function identifier) - msg.value (uint): number of wei sent with the message - now (uint): current block timestamp (alias for block.timestamp) - tx.gasprice (uint): gas price of the transaction - tx.origin (address): sender of the transaction (full call chain) ### Constructor of Solidity In solidity you can create construtor by use **constructor()** - example ``` contract Mycontract { uint a; constructor(unit _a) public { _a = a; } } ``` ### Declaring function in solidity To declaring function in solidity use **function Name()** ``` contract Mycontract { uint value; function getValue() external view returns(uint) { return value; } function setValue(uint _value) external { value = _value; } } ``` note: - function **with view** for view only - function **without view** for modifies data - **public** - Public functions are part of the contract interface and can be either called internally or via messages. For public state variables, an automatic getter function is generated. - **external** - External functions are part of the contract interface, which means they can be called from other contracts and via transactions. An external function f cannot be called internally (i.e. f()does not work, but this.f() works). External functions are sometimes more efficient when they receive large arrays of data. - **internal** - Those functions and state variables can only be accessed internally (i.e. from within the current contract or contracts deriving from it), without using this. - **private** - Private functions and state variables are only visible for the contract they are defined in and not in derived contracts. ### Array of solidity - Storage arrays Use to store data into blockchain ``` contract MyContract { uint[] myArray; function foo() external { myArray.push(2); // add value to array myArray.push(3); myArray[0]; // read array element myArray[1] = 3; // change array value delete myArray[1]; // delete array element for(uint i = 0; i<myArray.lenght; i++) { myArray[i] } } } ``` - Memory arrays Use to store data temporary ``` contract MyContract { function foo() external { uint[] memory myArray = new uint[](10); myArray[1] = 10; // use can add value only with this method myArray[5]; read array element delete myArray[1]; deleate array element } } ``` - Array arguments and return arrays from function Use array in function ``` contract MyContract { function foo(uint[] calldata _myArray) external { } function bar(uint[] memory _myArray) public { } function foobar(uint[] memory _myArray) internal { } function fool(uint[] memory _myArray) public returns(uint[] memory) { } } ``` ### Mapping in Solidity ``` contract MyContract { // mapping mapping(address => uint) balances; //nested mapping mapping(address => mapping(address => bool) approved; //array in mapping mapping(address => uint[]) score; function foo() external { // add balances[msg.sender] = 100; // read balances[msg.send]; // update balances[msge.value] = 120; // delete delete balances[msg.sender]; // default value balances[someAddressThatDoNotExit] => 0 } function bar(address spender) external { // add approved[msg.sender][spender] = true; // read approved[msg.sender][spender]; //update approved[msg.sender][spender] = false; //delete delete approved[msg.sender][spender]; } function foolbar() external { //add score[msg.sender].push(16); score[msg.sender].push(76); //read score[msg.sender][0]; //update score[msg.sender][0] = 80; //delete delete score[msg.sender][1]; } } ``` ### Stuct in Solidity ``` contract MyContract { struct User { address addr; uint score; string name; } User[] users; mapping(addrees => User) userList; function foo(string calldata _name) external { //add User memory user1 = User(msg.send, 20, _name); User memory user2 = User(name: _name, score: 20, addr: msg.sender); //read user1.addr; //update user2.score = 60 //delete delete user1; //add struct to array users.push(user1) //add strct to mapping userList[msg.sender] = user2; } } ```
addreadupdatedeleteadd struct to arrayadd strct to mapping
function foo(string calldata _name) external { User memory user1 = User(msg.send, 20, _name); User memory user2 = User(name: _name, score: 20, addr: msg.sender); user1.addr; user2.score = 60 delete user1; users.push(user1) userList[msg.sender] = user2; }
15,806,518
// 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; } }
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; }
15,809,853
./partial_match/1/0xB31342C51194671dc6B650C88E76b1d029aC2f0F/sources/BitsafeToken.sol
Destroy tokens from other account Remove `_value` tokens from the system irreversibly on behalf of `_from`. _from the address of the sender _value the amount of money to burn/
function burnFrom(address _from, uint256 _value) public returns (bool) { emit Burn(_from, _value); return true; }
2,843,684
./full_match/77/0xce456ea912230DdC2105e871d4df038457dcd7Dc/sources/deploy/contracts/oracle/chainlink/ChainlinkPriceFeed.sol
Remove the address of aggregator associated to a price identifier priceIdentifier Price feed identifier/
function removeAggregator(bytes32 priceIdentifier) external override onlyMaintainer { require( address(aggregators[priceIdentifier]) != address(0), 'Price identifier does not exist' ); delete aggregators[priceIdentifier]; emit RemoveAggregator(priceIdentifier); }
5,049,029
pragma solidity ^0.4.24; contract BetList { constructor() payable public { } struct Bet { uint id; address challenger; address accepter; string name; string conditions; uint price; } mapping (uint => Bet) public bets; uint betCounter; event LogPublishBet( uint indexed _id, address indexed _challenger, string _name, uint _price ); event LogAcceptBet( uint indexed _id, address indexed _challenger, address indexed _accepter, string _name, uint _price ); event LogResolveBet( uint indexed _id, address indexed _challenger, address indexed _accepter, string _name, uint _payout ); // Publish a new bet function publishBet(string _name, string _conditions) payable public { // The challenger must deposit his bet require(msg.value>0); uint _price= msg.value; // A new bet betCounter++; // Store this bet into the contract bets[betCounter] = Bet( betCounter, msg.sender, 0x0, _name, _conditions, _price ); // Trigger a log event emit LogPublishBet(betCounter, msg.sender, _name, _price); } // Fetch the total number of bets in the contract function getNumberOfBets() public view returns (uint) { return betCounter; } // Fetch and return all bet IDs for bets that are still available function getAvailableBets() public view returns (uint[]) { uint[] memory betIds = new uint[](betCounter); uint numberOfAvailableBets = 0; // Iterate over all bets for(uint i = 1; i <= betCounter; i++) { // Keep the ID if the bet is still available if(bets[i].accepter == 0x0) { betIds[numberOfAvailableBets] = bets[i].id; numberOfAvailableBets++; } } uint[] memory availableBets = new uint[](numberOfAvailableBets); // Copy the betIds array into a smaller availableBets array to get rid of empty indexes for(uint j = 0; j < numberOfAvailableBets; j++) { availableBets[j] = betIds[j]; } return availableBets; } // Accept a bet function acceptBet(uint _id) payable public { // Check whether there is a bet published require(betCounter > 0); // Check that the bet exists require(_id > 0 && _id <= betCounter); // Retrieve the bet Bet storage bet = bets[_id]; // Check that the bet has not been accepted yet require(bet.accepter == 0x0); // Don't allow the challenger to accept his own bet require(msg.sender != bet.challenger); // The accepter must deposit his bet // require(msg.value == bet.price); bet.accepter = msg.sender; // Trigger a log event emit LogAcceptBet(_id, bet.challenger, bet.accepter, bet.name, bet.price); } // Only the referee can resolve bets function resolveBet(uint _id, bool challengerWins ) payable public { // Retrieve the bet Bet storage bet = bets[_id]; // The bet must not be open require(bet.accepter != 0x0); // The bet must not have been paid out yet require(bet.price > 0); // Execute payout if (challengerWins) { // challenger wins bet.challenger.transfer(bet.price * 2); } else { // accepter wins bet.accepter.transfer(bet.price * 2); } // Set the bet status as paid out (price = 0) uint256 payout = bet.price * 2; bet.price = 0; // Trigger a log event emit LogResolveBet(_id, bet.challenger, bet.accepter, bet.name, payout); } // Only the referee can terminate this contract function terminate() payable public { // Cancel all open bets and return the deposits for(uint i = 1; i <= betCounter; i++) { if(bets[i].price > 0) { // The bet has not yet been paid out if(bets[i].accepter == 0x0) { // The bet has only a challenger. Return ether to him. bets[i].challenger.transfer(bets[i].price); } else { // bet has both a challenger and an accepter, but is not yet resolved. Cancel the bet and return deposits to both. bets[i].challenger.transfer(bets[i].price); bets[i].accepter.transfer(bets[i].price); } } } } }
Only the referee can resolve bets Retrieve the bet The bet must not be open The bet must not have been paid out yet Execute payout
function resolveBet(uint _id, bool challengerWins ) payable public { Bet storage bet = bets[_id]; require(bet.accepter != 0x0); require(bet.price > 0); bet.challenger.transfer(bet.price * 2); bet.accepter.transfer(bet.price * 2); } bet.price = 0;
14,015,443
./partial_match/1/0x6f6B838616D0a2b35f0D5Bb434f8466e64d915bc/sources/EscapeTheAgenda.sol
Owner quota for the team and giveaways
function ownerMint(uint256 numberOfTokens, address _receiver) public nonReentrant onlyOwner canMintAGND(numberOfTokens) { _safeMint(_receiver, numberOfTokens); }
9,316,305
./full_match/1/0x3D4a70e5F355EAd0690213Ae9909f3Dc41236E3C/sources/@gearbox-protocol/integrations-v2/contracts/adapters/convex/ConvexV1_BaseRewardPool.sol
Sends an order to withdraw all Convex LP tokens from the BaseRewardPool claim Whether to claim rewards while withdrawing The input token does need to be disabled, because this spends the entire balance
function withdrawAll(bool claim) external override { }
16,431,951
pragma solidity ^0.4.13; interface ERC721Enumerable /* is ERC721 */ { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() public view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId); } interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } 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; } } interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transfered /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract LicenseAccessControl { /** * @notice ContractUpgrade is the event that will be emitted if we set a new contract address */ event ContractUpgrade(address newContract); event Paused(); event Unpaused(); /** * @notice CEO's address FOOBAR */ address public ceoAddress; /** * @notice CFO's address */ address public cfoAddress; /** * @notice COO's address */ address public cooAddress; /** * @notice withdrawal address */ address public withdrawalAddress; bool public paused = false; /** * @dev Modifier to make a function only callable by the CEO */ modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /** * @dev Modifier to make a function only callable by the CFO */ modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /** * @dev Modifier to make a function only callable by the COO */ modifier onlyCOO() { require(msg.sender == cooAddress); _; } /** * @dev Modifier to make a function only callable by C-level execs */ modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /** * @dev Modifier to make a function only callable by CEO or CFO */ modifier onlyCEOOrCFO() { require( msg.sender == cfoAddress || msg.sender == ceoAddress ); _; } /** * @dev Modifier to make a function only callable by CEO or COO */ modifier onlyCEOOrCOO() { require( msg.sender == cooAddress || msg.sender == ceoAddress ); _; } /** * @notice Sets a new CEO * @param _newCEO - the address of the new CEO */ function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /** * @notice Sets a new CFO * @param _newCFO - the address of the new CFO */ function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /** * @notice Sets a new COO * @param _newCOO - the address of the new COO */ function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /** * @notice Sets a new withdrawalAddress * @param _newWithdrawalAddress - the address where we'll send the funds */ function setWithdrawalAddress(address _newWithdrawalAddress) external onlyCEO { require(_newWithdrawalAddress != address(0)); withdrawalAddress = _newWithdrawalAddress; } /** * @notice Withdraw the balance to the withdrawalAddress * @dev We set a withdrawal address seperate from the CFO because this allows us to withdraw to a cold wallet. */ function withdrawBalance() external onlyCEOOrCFO { require(withdrawalAddress != address(0)); withdrawalAddress.transfer(this.balance); } /** Pausable functionality adapted from OpenZeppelin **/ /** * @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); _; } /** * @notice called by any C-level to pause, triggers stopped state */ function pause() public onlyCLevel whenNotPaused { paused = true; Paused(); } /** * @notice called by the CEO to unpause, returns to normal state */ function unpause() public onlyCEO whenPaused { paused = false; Unpaused(); } } contract LicenseBase is LicenseAccessControl { /** * @notice Issued is emitted when a new license is issued */ event LicenseIssued( address indexed owner, address indexed purchaser, uint256 licenseId, uint256 productId, uint256 attributes, uint256 issuedTime, uint256 expirationTime, address affiliate ); event LicenseRenewal( address indexed owner, address indexed purchaser, uint256 licenseId, uint256 productId, uint256 expirationTime ); struct License { uint256 productId; uint256 attributes; uint256 issuedTime; uint256 expirationTime; address affiliate; } /** * @notice All licenses in existence. * @dev The ID of each license is an index in this array. */ License[] licenses; /** internal **/ function _isValidLicense(uint256 _licenseId) internal view returns (bool) { return licenseProductId(_licenseId) != 0; } /** anyone **/ /** * @notice Get a license's productId * @param _licenseId the license id */ function licenseProductId(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].productId; } /** * @notice Get a license's attributes * @param _licenseId the license id */ function licenseAttributes(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].attributes; } /** * @notice Get a license's issueTime * @param _licenseId the license id */ function licenseIssuedTime(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].issuedTime; } /** * @notice Get a license's issueTime * @param _licenseId the license id */ function licenseExpirationTime(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].expirationTime; } /** * @notice Get a the affiliate credited for the sale of this license * @param _licenseId the license id */ function licenseAffiliate(uint256 _licenseId) public view returns (address) { return licenses[_licenseId].affiliate; } /** * @notice Get a license's info * @param _licenseId the license id */ function licenseInfo(uint256 _licenseId) public view returns (uint256, uint256, uint256, uint256, address) { return ( licenseProductId(_licenseId), licenseAttributes(_licenseId), licenseIssuedTime(_licenseId), licenseExpirationTime(_licenseId), licenseAffiliate(_licenseId) ); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract AffiliateProgram is Pausable { using SafeMath for uint256; event AffiliateCredit( // The address of the affiliate address affiliate, // The store's ID of what was sold (e.g. a tokenId) uint256 productId, // The amount owed this affiliate in this sale uint256 amount ); event Withdraw(address affiliate, address to, uint256 amount); event Whitelisted(address affiliate, uint256 amount); event RateChanged(uint256 rate, uint256 amount); // @notice A mapping from affiliate address to their balance mapping (address => uint256) public balances; // @notice A mapping from affiliate address to the time of last deposit mapping (address => uint256) public lastDepositTimes; // @notice The last deposit globally uint256 public lastDepositTime; // @notice The maximum rate for any affiliate // @dev The hard-coded maximum affiliate rate (in basis points) // All rates are measured in basis points (1/100 of a percent) // Values 0-10,000 map to 0%-100% uint256 private constant hardCodedMaximumRate = 5000; // @notice The commission exiration time // @dev Affiliate commissions expire if they are unclaimed after this amount of time uint256 private constant commissionExpiryTime = 30 days; // @notice The baseline affiliate rate (in basis points) for non-whitelisted referrals uint256 public baselineRate = 0; // @notice A mapping from whitelisted referrals to their individual rates mapping (address => uint256) public whitelistRates; // @notice The maximum rate for any affiliate // @dev overrides individual rates. This can be used to clip the rate used in bulk, if necessary uint256 public maximumRate = 5000; // @notice The address of the store selling products address public storeAddress; // @notice The contract is retired // @dev If we decide to retire this program, this value will be set to true // and then the contract cannot be unpaused bool public retired = false; /** * @dev Modifier to make a function only callable by the store or the owner */ modifier onlyStoreOrOwner() { require( msg.sender == storeAddress || msg.sender == owner); _; } /** * @dev AffiliateProgram constructor - keeps the address of it's parent store * and pauses the contract */ function AffiliateProgram(address _storeAddress) public { require(_storeAddress != address(0)); storeAddress = _storeAddress; paused = true; } /** * @notice Exposes that this contract thinks it is an AffiliateProgram */ function isAffiliateProgram() public pure returns (bool) { return true; } /** * @notice returns the commission rate for a sale * * @dev rateFor returns the rate which should be used to calculate the comission * for this affiliate/sale combination, in basis points (1/100th of a percent). * * We may want to completely blacklist a particular address (e.g. a known bad actor affilite). * To that end, if the whitelistRate is exactly 1bp, we use that as a signal for blacklisting * and return a rate of zero. The upside is that we can completely turn off * sending transactions to a particular address when this is needed. The * downside is that you can't issued 1/100th of a percent commission. * However, since this is such a small amount its an acceptable tradeoff. * * This implementation does not use the _productId, _pruchaseId, * _purchaseAmount, but we include them here as part of the protocol, because * they could be useful in more advanced affiliate programs. * * @param _affiliate - the address of the affiliate to check for */ function rateFor( address _affiliate, uint256 /*_productId*/, uint256 /*_purchaseId*/, uint256 /*_purchaseAmount*/) public view returns (uint256) { uint256 whitelistedRate = whitelistRates[_affiliate]; if(whitelistedRate > 0) { // use 1 bp as a blacklist signal if(whitelistedRate == 1) { return 0; } else { return Math.min256(whitelistedRate, maximumRate); } } else { return Math.min256(baselineRate, maximumRate); } } /** * @notice cutFor returns the affiliate cut for a sale * @dev cutFor returns the cut (amount in wei) to give in comission to the affiliate * * @param _affiliate - the address of the affiliate to check for * @param _productId - the productId in the sale * @param _purchaseId - the purchaseId in the sale * @param _purchaseAmount - the purchaseAmount */ function cutFor( address _affiliate, uint256 _productId, uint256 _purchaseId, uint256 _purchaseAmount) public view returns (uint256) { uint256 rate = rateFor( _affiliate, _productId, _purchaseId, _purchaseAmount); require(rate <= hardCodedMaximumRate); return (_purchaseAmount.mul(rate)).div(10000); } /** * @notice credit an affiliate for a purchase * @dev credit accepts eth and credits the affiliate's balance for the amount * * @param _affiliate - the address of the affiliate to credit * @param _purchaseId - the purchaseId of the sale */ function credit( address _affiliate, uint256 _purchaseId) public onlyStoreOrOwner whenNotPaused payable { require(msg.value > 0); require(_affiliate != address(0)); balances[_affiliate] += msg.value; lastDepositTimes[_affiliate] = now; // solium-disable-line security/no-block-members lastDepositTime = now; // solium-disable-line security/no-block-members AffiliateCredit(_affiliate, _purchaseId, msg.value); } /** * @dev _performWithdraw performs a withdrawal from address _from and * transfers it to _to. This can be different because we allow the owner * to withdraw unclaimed funds after a period of time. * * @param _from - the address to subtract balance from * @param _to - the address to transfer ETH to */ function _performWithdraw(address _from, address _to) private { require(balances[_from] > 0); uint256 balanceValue = balances[_from]; balances[_from] = 0; _to.transfer(balanceValue); Withdraw(_from, _to, balanceValue); } /** * @notice withdraw * @dev withdraw the msg.sender's balance */ function withdraw() public whenNotPaused { _performWithdraw(msg.sender, msg.sender); } /** * @notice withdraw from a specific account * @dev withdrawFrom allows the owner to withdraw an affiliate's unclaimed * ETH, after the alotted time. * * This function can be called even if the contract is paused * * @param _affiliate - the address of the affiliate * @param _to - the address to send ETH to */ function withdrawFrom(address _affiliate, address _to) onlyOwner public { // solium-disable-next-line security/no-block-members require(now > lastDepositTimes[_affiliate].add(commissionExpiryTime)); _performWithdraw(_affiliate, _to); } /** * @notice retire the contract (dangerous) * @dev retire - withdraws the entire balance and marks the contract as retired, which * prevents unpausing. * * If no new comissions have been deposited for the alotted time, * then the owner may pause the program and retire this contract. * This may only be performed once as the contract cannot be unpaused. * * We do this as an alternative to selfdestruct, because certain operations * can still be performed after the contract has been selfdestructed, such as * the owner withdrawing ETH accidentally sent here. */ function retire(address _to) onlyOwner whenPaused public { // solium-disable-next-line security/no-block-members require(now > lastDepositTime.add(commissionExpiryTime)); _to.transfer(this.balance); retired = true; } /** * @notice whitelist an affiliate address * @dev whitelist - white listed affiliates can receive a different * rate than the general public (whitelisted accounts would generally get a * better rate). * @param _affiliate - the affiliate address to whitelist * @param _rate - the rate, in basis-points (1/100th of a percent) to give this affiliate in each sale. NOTE: a rate of exactly 1 is the signal to blacklist this affiliate. That is, a rate of 1 will set the commission to 0. */ function whitelist(address _affiliate, uint256 _rate) onlyOwner public { require(_rate <= hardCodedMaximumRate); whitelistRates[_affiliate] = _rate; Whitelisted(_affiliate, _rate); } /** * @notice set the rate for non-whitelisted affiliates * @dev setBaselineRate - sets the baseline rate for any affiliate that is not whitelisted * @param _newRate - the rate, in bp (1/100th of a percent) to give any non-whitelisted affiliate. Set to zero to "turn off" */ function setBaselineRate(uint256 _newRate) onlyOwner public { require(_newRate <= hardCodedMaximumRate); baselineRate = _newRate; RateChanged(0, _newRate); } /** * @notice set the maximum rate for any affiliate * @dev setMaximumRate - Set the maximum rate for any affiliate, including whitelists. That is, this overrides individual rates. * @param _newRate - the rate, in bp (1/100th of a percent) */ function setMaximumRate(uint256 _newRate) onlyOwner public { require(_newRate <= hardCodedMaximumRate); maximumRate = _newRate; RateChanged(1, _newRate); } /** * @notice unpause the contract * @dev called by the owner to unpause, returns to normal state. Will not * unpause if the contract is retired. */ function unpause() onlyOwner whenPaused public { require(!retired); paused = false; Unpause(); } } contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _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 safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) external; function setApprovalForAll(address _to, bool _approved) external; function getApproved(uint256 _tokenId) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool); } contract LicenseInventory is LicenseBase { using SafeMath for uint256; event ProductCreated( uint256 id, uint256 price, uint256 available, uint256 supply, uint256 interval, bool renewable ); event ProductInventoryAdjusted(uint256 productId, uint256 available); event ProductPriceChanged(uint256 productId, uint256 price); event ProductRenewableChanged(uint256 productId, bool renewable); /** * @notice Product defines a product * * renewable: There may come a time when we which to disable the ability to renew a subscription. For example, a plan we no longer wish to support. Obviously care needs to be taken with how we communicate this to customers, but contract-wise, we want to support the ability to discontinue renewal of certain plans. */ struct Product { uint256 id; uint256 price; uint256 available; uint256 supply; uint256 sold; uint256 interval; bool renewable; } // @notice All products in existence uint256[] public allProductIds; // @notice A mapping from product ids to Products mapping (uint256 => Product) public products; /*** internal ***/ /** * @notice _productExists checks to see if a product exists */ function _productExists(uint256 _productId) internal view returns (bool) { return products[_productId].id != 0; } function _productDoesNotExist(uint256 _productId) internal view returns (bool) { return products[_productId].id == 0; } function _createProduct( uint256 _productId, uint256 _initialPrice, uint256 _initialInventoryQuantity, uint256 _supply, uint256 _interval) internal { require(_productDoesNotExist(_productId)); require(_initialInventoryQuantity <= _supply); Product memory _product = Product({ id: _productId, price: _initialPrice, available: _initialInventoryQuantity, supply: _supply, sold: 0, interval: _interval, renewable: _interval == 0 ? false : true }); products[_productId] = _product; allProductIds.push(_productId); ProductCreated( _product.id, _product.price, _product.available, _product.supply, _product.interval, _product.renewable ); } function _incrementInventory( uint256 _productId, uint256 _inventoryAdjustment) internal { require(_productExists(_productId)); uint256 newInventoryLevel = products[_productId].available.add(_inventoryAdjustment); // A supply of "0" means "unlimited". Otherwise we need to ensure that we're not over-creating this product if(products[_productId].supply > 0) { // you have to take already sold into account require(products[_productId].sold.add(newInventoryLevel) <= products[_productId].supply); } products[_productId].available = newInventoryLevel; } function _decrementInventory( uint256 _productId, uint256 _inventoryAdjustment) internal { require(_productExists(_productId)); uint256 newInventoryLevel = products[_productId].available.sub(_inventoryAdjustment); // unnecessary because we're using SafeMath and an unsigned int // require(newInventoryLevel >= 0); products[_productId].available = newInventoryLevel; } function _clearInventory(uint256 _productId) internal { require(_productExists(_productId)); products[_productId].available = 0; } function _setPrice(uint256 _productId, uint256 _price) internal { require(_productExists(_productId)); products[_productId].price = _price; } function _setRenewable(uint256 _productId, bool _isRenewable) internal { require(_productExists(_productId)); products[_productId].renewable = _isRenewable; } function _purchaseOneUnitInStock(uint256 _productId) internal { require(_productExists(_productId)); require(availableInventoryOf(_productId) > 0); // lower inventory _decrementInventory(_productId, 1); // record that one was sold products[_productId].sold = products[_productId].sold.add(1); } function _requireRenewableProduct(uint256 _productId) internal view { // productId must exist require(_productId != 0); // You can only renew a subscription product require(isSubscriptionProduct(_productId)); // The product must currently be renewable require(renewableOf(_productId)); } /*** public ***/ /** executives-only **/ /** * @notice createProduct creates a new product in the system * @param _productId - the id of the product to use (cannot be changed) * @param _initialPrice - the starting price (price can be changed) * @param _initialInventoryQuantity - the initial inventory (inventory can be changed) * @param _supply - the total supply - use `0` for "unlimited" (cannot be changed) */ function createProduct( uint256 _productId, uint256 _initialPrice, uint256 _initialInventoryQuantity, uint256 _supply, uint256 _interval) external onlyCEOOrCOO { _createProduct( _productId, _initialPrice, _initialInventoryQuantity, _supply, _interval); } /** * @notice incrementInventory - increments the inventory of a product * @param _productId - the product id * @param _inventoryAdjustment - the amount to increment */ function incrementInventory( uint256 _productId, uint256 _inventoryAdjustment) external onlyCLevel { _incrementInventory(_productId, _inventoryAdjustment); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice decrementInventory removes inventory levels for a product * @param _productId - the product id * @param _inventoryAdjustment - the amount to decrement */ function decrementInventory( uint256 _productId, uint256 _inventoryAdjustment) external onlyCLevel { _decrementInventory(_productId, _inventoryAdjustment); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice clearInventory clears the inventory of a product. * @dev decrementInventory verifies inventory levels, whereas this method * simply sets the inventory to zero. This is useful, for example, if an * executive wants to take a product off the market quickly. There could be a * race condition with decrementInventory where a product is sold, which could * cause the admins decrement to fail (because it may try to decrement more * than available). * * @param _productId - the product id */ function clearInventory(uint256 _productId) external onlyCLevel { _clearInventory(_productId); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice setPrice - sets the price of a product * @param _productId - the product id * @param _price - the product price */ function setPrice(uint256 _productId, uint256 _price) external onlyCLevel { _setPrice(_productId, _price); ProductPriceChanged(_productId, _price); } /** * @notice setRenewable - sets if a product is renewable * @param _productId - the product id * @param _newRenewable - the new renewable setting */ function setRenewable(uint256 _productId, bool _newRenewable) external onlyCLevel { _setRenewable(_productId, _newRenewable); ProductRenewableChanged(_productId, _newRenewable); } /** anyone **/ /** * @notice The price of a product * @param _productId - the product id */ function priceOf(uint256 _productId) public view returns (uint256) { return products[_productId].price; } /** * @notice The available inventory of a product * @param _productId - the product id */ function availableInventoryOf(uint256 _productId) public view returns (uint256) { return products[_productId].available; } /** * @notice The total supply of a product * @param _productId - the product id */ function totalSupplyOf(uint256 _productId) public view returns (uint256) { return products[_productId].supply; } /** * @notice The total sold of a product * @param _productId - the product id */ function totalSold(uint256 _productId) public view returns (uint256) { return products[_productId].sold; } /** * @notice The renewal interval of a product in seconds * @param _productId - the product id */ function intervalOf(uint256 _productId) public view returns (uint256) { return products[_productId].interval; } /** * @notice Is this product renewable? * @param _productId - the product id */ function renewableOf(uint256 _productId) public view returns (bool) { return products[_productId].renewable; } /** * @notice The product info for a product * @param _productId - the product id */ function productInfo(uint256 _productId) public view returns (uint256, uint256, uint256, uint256, bool) { return ( priceOf(_productId), availableInventoryOf(_productId), totalSupplyOf(_productId), intervalOf(_productId), renewableOf(_productId)); } /** * @notice Get all product ids */ function getAllProductIds() public view returns (uint256[]) { return allProductIds; } /** * @notice returns the total cost to renew a product for a number of cycles * @dev If a product is a subscription, the interval defines the period of * time, in seconds, users can subscribe for. E.g. 1 month or 1 year. * _numCycles is the number of these intervals we want to use in the * calculation of the price. * * We require that the end user send precisely the amount required (instead * of dealing with excess refunds). This method is public so that clients can * read the exact amount our contract expects to receive. * * @param _productId - the product we're calculating for * @param _numCycles - the number of cycles to calculate for */ function costForProductCycles(uint256 _productId, uint256 _numCycles) public view returns (uint256) { return priceOf(_productId).mul(_numCycles); } /** * @notice returns if this product is a subscription or not * @dev Some products are subscriptions and others are not. An interval of 0 * means the product is not a subscription * @param _productId - the product we're checking */ function isSubscriptionProduct(uint256 _productId) public view returns (bool) { return intervalOf(_productId) > 0; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC165 { /// @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. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract LicenseOwnership is LicenseInventory, ERC721, ERC165, ERC721Metadata, ERC721Enumerable { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // 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 address to operator address to approval mapping (address => mapping (address => bool)) private operatorApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /*** Constants ***/ // Configure these for your own deployment string public constant NAME = "Dottabot"; string public constant SYMBOL = "DOTTA"; string public tokenMetadataBaseURI = "https://api.dottabot.com/"; /** * @notice token's name */ function name() external pure returns (string) { return NAME; } /** * @notice symbols's name */ function symbol() external pure returns (string) { return SYMBOL; } function implementsERC721() external pure returns (bool) { return true; } function tokenURI(uint256 _tokenId) external view returns (string infoUrl) { return Strings.strConcat( tokenMetadataBaseURI, Strings.uint2str(_tokenId)); } function supportsInterface( bytes4 interfaceID) // solium-disable-line dotta/underscore-function-arguments external view returns (bool) { return interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0x5b5e139f || // ERC721Metadata interfaceID == 0x6466353c || // ERC-721 on 3/7/2018 interfaceID == 0x780e9d63; // ERC721Enumerable } function setTokenMetadataBaseURI(string _newBaseURI) external onlyCEOOrCOO { tokenMetadataBaseURI = _newBaseURI; } /** * @notice Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @notice Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @notice Enumerate valid NFTs * @dev Our Licenses are kept in an array and each new License-token is just * the next element in the array. This method is required for ERC721Enumerable * which may support more complicated storage schemes. However, in our case the * _index is the tokenId * @param _index A counter less than `totalSupply()` * @return The token identifier for the `_index`th NFT */ function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index < totalSupply()); return _index; } /** * @notice 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 ownedTokens[_owner].length; } /** * @notice Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @notice Enumerate NFTs assigned to an owner * @dev Throws if `_index` >= `balanceOf(_owner)` or if * `_owner` is the zero address, representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them * @param _index A counter less than `balanceOf(_owner)` * @return The token identifier for the `_index`th NFT assigned to `_owner`, */ function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @notice 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; } /** * @notice Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @notice Tells whether the msg.sender is approved to transfer the given token ID or not * Checks both for specific approval and operator approval * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether transfer by msg.sender is approved for the given token ID or not */ function isSenderApprovedFor(uint256 _tokenId) internal view returns (bool) { return ownerOf(_tokenId) == msg.sender || isSpecificallyApprovedFor(msg.sender, _tokenId) || isApprovedForAll(ownerOf(_tokenId), msg.sender); } /** * @notice Tells whether the msg.sender is approved for the given token ID or not * @param _asker address of asking for approval * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isSpecificallyApprovedFor(address _asker, uint256 _tokenId) internal view returns (bool) { return getApproved(_tokenId) == _asker; } /** * @notice 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]; } /** * @notice Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) external whenNotPaused onlyOwnerOf(_tokenId) { _clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @notice Approves another address to claim for the ownership of the given token ID * @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) external whenNotPaused onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (getApproved(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @notice Enable or disable approval for a third party ("operator") to manage all your assets * @dev Emits the ApprovalForAll event * @param _to Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval */ function setApprovalForAll(address _to, bool _approved) external whenNotPaused { if(_approved) { approveAll(_to); } else { disapproveAll(_to); } } /** * @notice Approves another address to claim for the ownership of any tokens owned by this account * @param _to address to be approved for the given token ID */ function approveAll(address _to) public whenNotPaused { require(_to != msg.sender); require(_to != address(0)); operatorApprovals[msg.sender][_to] = true; ApprovalForAll(msg.sender, _to, true); } /** * @notice Removes approval for another address to claim for the ownership of any * tokens owned by this account. * @dev Note that this only removes the operator approval and * does not clear any independent, specific approvals of token transfers to this address * @param _to address to be disapproved for the given token ID */ function disapproveAll(address _to) public whenNotPaused { require(_to != msg.sender); delete operatorApprovals[msg.sender][_to]; ApprovalForAll(msg.sender, _to, false); } /** * @notice Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) external whenNotPaused { require(isSenderApprovedFor(_tokenId)); _clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @notice Transfer a token owned by another address, for which the calling address has * previously been granted transfer approval by the owner. * @param _from The address that owns the token * @param _to The address that will take ownership of the token. Can be any address, including the caller * @param _tokenId The ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { require(isSenderApprovedFor(_tokenId)); require(ownerOf(_tokenId) == _from); _clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId); } /** * @notice Transfers the ownership of an NFT from one address to another address * @dev Throws unless `msg.sender` is the current owner, an authorized * operator, or the approved address for this NFT. Throws if `_from` is * not the current owner. Throws if `_to` is the zero address. Throws if * `_tokenId` is not a valid NFT. When transfer is complete, this function * checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public whenNotPaused { require(_to != address(0)); require(_isValidLicense(_tokenId)); transferFrom(_from, _to, _tokenId); if (_isContract(_to)) { bytes4 tokenReceiverResponse = ERC721TokenReceiver(_to).onERC721Received.gas(50000)( _from, _tokenId, _data ); require(tokenReceiverResponse == bytes4(keccak256("onERC721Received(address,uint256,bytes)"))); } } /* * @notice Transfers the ownership of an NFT from one address to another address * @dev This works identically to the other function with an extra data parameter, * except this function just sets data to "" * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @notice Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); _addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @notice Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function _clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); require(_isValidLicense(_tokenId)); _clearApproval(_from, _tokenId); _removeToken(_from, _tokenId); _addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @notice Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function _clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @notice Internal function to add a token ID to the list of a given address * @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 _addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @notice Internal function to remove a token ID from the list of a given address * @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 _removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } function _isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } contract LicenseSale is LicenseOwnership { AffiliateProgram public affiliateProgram; /** * @notice We credit affiliates for renewals that occur within this time of * original purchase. E.g. If this is set to 1 year, and someone subscribes to * a monthly plan, the affiliate will receive credits for that whole year, as * the user renews their plan */ uint256 public renewalsCreditAffiliatesFor = 1 years; /** internal **/ function _performPurchase( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes, address _affiliate) internal returns (uint) { _purchaseOneUnitInStock(_productId); return _createLicense( _productId, _numCycles, _assignee, _attributes, _affiliate ); } function _createLicense( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes, address _affiliate) internal returns (uint) { // You cannot create a subscription license with zero cycles if(isSubscriptionProduct(_productId)) { require(_numCycles != 0); } // Non-subscription products have an expiration time of 0, meaning "no-expiration" uint256 expirationTime = isSubscriptionProduct(_productId) ? now.add(intervalOf(_productId).mul(_numCycles)) : // solium-disable-line security/no-block-members 0; License memory _license = License({ productId: _productId, attributes: _attributes, issuedTime: now, // solium-disable-line security/no-block-members expirationTime: expirationTime, affiliate: _affiliate }); uint256 newLicenseId = licenses.push(_license) - 1; // solium-disable-line zeppelin/no-arithmetic-operations LicenseIssued( _assignee, msg.sender, newLicenseId, _license.productId, _license.attributes, _license.issuedTime, _license.expirationTime, _license.affiliate); _mint(_assignee, newLicenseId); return newLicenseId; } function _handleAffiliate( address _affiliate, uint256 _productId, uint256 _licenseId, uint256 _purchaseAmount) internal { uint256 affiliateCut = affiliateProgram.cutFor( _affiliate, _productId, _licenseId, _purchaseAmount); if(affiliateCut > 0) { require(affiliateCut < _purchaseAmount); affiliateProgram.credit.value(affiliateCut)(_affiliate, _licenseId); } } function _performRenewal(uint256 _tokenId, uint256 _numCycles) internal { // You cannot renew a non-expiring license // ... but in what scenario can this happen? // require(licenses[_tokenId].expirationTime != 0); uint256 productId = licenseProductId(_tokenId); // If our expiration is in the future, renewing adds time to that future expiration // If our expiration has passed already, then we use `now` as the base. uint256 renewalBaseTime = Math.max256(now, licenses[_tokenId].expirationTime); // We assume that the payment has been validated outside of this function uint256 newExpirationTime = renewalBaseTime.add(intervalOf(productId).mul(_numCycles)); licenses[_tokenId].expirationTime = newExpirationTime; LicenseRenewal( ownerOf(_tokenId), msg.sender, _tokenId, productId, newExpirationTime ); } function _affiliateProgramIsActive() internal view returns (bool) { return affiliateProgram != address(0) && affiliateProgram.storeAddress() == address(this) && !affiliateProgram.paused(); } /** executives **/ function setAffiliateProgramAddress(address _address) external onlyCEO { AffiliateProgram candidateContract = AffiliateProgram(_address); require(candidateContract.isAffiliateProgram()); affiliateProgram = candidateContract; } function setRenewalsCreditAffiliatesFor(uint256 _newTime) external onlyCEO { renewalsCreditAffiliatesFor = _newTime; } function createPromotionalPurchase( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes ) external onlyCEOOrCOO whenNotPaused returns (uint256) { return _performPurchase( _productId, _numCycles, _assignee, _attributes, address(0)); } function createPromotionalRenewal( uint256 _tokenId, uint256 _numCycles ) external onlyCEOOrCOO whenNotPaused { uint256 productId = licenseProductId(_tokenId); _requireRenewableProduct(productId); return _performRenewal(_tokenId, _numCycles); } /** anyone **/ /** * @notice Makes a purchase of a product. * @dev Requires that the value sent is exactly the price of the product * @param _productId - the product to purchase * @param _numCycles - the number of cycles being purchased. This number should be `1` for non-subscription products and the number of cycles for subscriptions. * @param _assignee - the address to assign the purchase to (doesn't have to be msg.sender) * @param _affiliate - the address to of the affiliate - use address(0) if none */ function purchase( uint256 _productId, uint256 _numCycles, address _assignee, address _affiliate ) external payable whenNotPaused returns (uint256) { require(_productId != 0); require(_numCycles != 0); require(_assignee != address(0)); // msg.value can be zero: free products are supported // Don't bother dealing with excess payments. Ensure the price paid is // accurate. No more, no less. require(msg.value == costForProductCycles(_productId, _numCycles)); // Non-subscription products should send a _numCycle of 1 -- you can't buy a // multiple quantity of a non-subscription product with this function if(!isSubscriptionProduct(_productId)) { require(_numCycles == 1); } // this can, of course, be gamed by malicious miners. But it's adequate for our application // Feel free to add your own strategies for product attributes // solium-disable-next-line security/no-block-members, zeppelin/no-arithmetic-operations uint256 attributes = uint256(keccak256(block.blockhash(block.number-1)))^_productId^(uint256(_assignee)); uint256 licenseId = _performPurchase( _productId, _numCycles, _assignee, attributes, _affiliate); if( priceOf(_productId) > 0 && _affiliate != address(0) && _affiliateProgramIsActive() ) { _handleAffiliate( _affiliate, _productId, licenseId, msg.value); } return licenseId; } /** * @notice Renews a subscription */ function renew( uint256 _tokenId, uint256 _numCycles ) external payable whenNotPaused { require(_numCycles != 0); require(ownerOf(_tokenId) != address(0)); uint256 productId = licenseProductId(_tokenId); _requireRenewableProduct(productId); // No excess payments. Ensure the price paid is exactly accurate. No more, // no less. uint256 renewalCost = costForProductCycles(productId, _numCycles); require(msg.value == renewalCost); _performRenewal(_tokenId, _numCycles); if( renewalCost > 0 && licenseAffiliate(_tokenId) != address(0) && _affiliateProgramIsActive() && licenseIssuedTime(_tokenId).add(renewalsCreditAffiliatesFor) > now ) { _handleAffiliate( licenseAffiliate(_tokenId), productId, _tokenId, msg.value); } } } contract LicenseCore is LicenseSale { address public newContractAddress; function LicenseCore() public { paused = true; ceoAddress = msg.sender; cooAddress = msg.sender; cfoAddress = msg.sender; withdrawalAddress = msg.sender; } function setNewAddress(address _v2Address) external onlyCEO whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } function() external { assert(false); } function unpause() public onlyCEO whenPaused { require(newContractAddress == address(0)); super.unpause(); } } library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } }
The total sold of a product _productId - the product id/
function totalSold(uint256 _productId) public view returns (uint256) { return products[_productId].sold; }
478,448
./full_match/1/0x023Cb563593da062848dD3460C0B72203d3e24a5/sources/src/ClaimManager.sol
Adjust current contract being used in the distribution mechanics
function setCurrentContract( address newContract ) external onlyRolesOrOwner(ADMIN_ROLE) { currentContract = newContract; }
8,485,118
pragma solidity ^0.5.0; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <[email protected]> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != address(0)); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != address(0)); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor (address[] memory _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i = 0; i < owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes memory data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes memory data) internal returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public view returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes memory data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public view returns (uint count) { for (uint i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint count) { for (uint i = 0; i < transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] memory _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
Returns total number of transactions after filers are applied. pending Include pending transactions. executed Include executed transactions. return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed) public view returns (uint count) { for (uint i = 0; i < transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; }
363,923
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } 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) external onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract EcroContract is Ownable { using SafeMath for uint256; //INVESTOR REPOSITORY mapping(address => uint256) internal balances; mapping (address => mapping(uint256=>uint256)) masterNodes; mapping (address => uint256[]) masterNodesDates; mapping (address => mapping (address => uint256)) internal allowed; mapping (address => uint256) internal totalAllowed; /** * @dev total number of tokens in existence */ uint256 internal totSupply; //COMMON function totalSupply() view public returns(uint256) { return totSupply; } function getTotalAllowed(address _owner) view public returns(uint256) { return totalAllowed[_owner]; } function setTotalAllowed(address _owner, uint256 _newValue) internal { totalAllowed[_owner]=_newValue; } function setTotalSupply(uint256 _newValue) internal { totSupply=_newValue; } function getMasterNodesDates(address _owner) view public returns(uint256[]) { return masterNodesDates[_owner]; } function getMasterNodes(address _owner, uint256 _date) view public returns(uint256) { return masterNodes[_owner][_date]; } function addMasterNodes(address _owner,uint256 _date,uint256 _amount) internal { masterNodesDates[_owner].push(_date); masterNodes[_owner][_date]=_amount; } function removeMasterNodes(address _owner,uint256 _date) internal { masterNodes[_owner][_date]=0; } /** * @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) view public returns(uint256) { return balances[_owner]; } function setBalanceOf(address _investor, uint256 _newValue) internal { require(_investor!=0x0000000000000000000000000000000000000000); balances[_investor]=_newValue; } /** * @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) view public returns(uint256) { require(msg.sender==_owner || msg.sender == _spender || msg.sender==getOwner()); return allowed[_owner][_spender]; } function setAllowance(address _owner, address _spender, uint256 _newValue) internal { require(_spender!=0x0000000000000000000000000000000000000000); uint256 newTotal = getTotalAllowed(_owner).sub(allowance(_owner, _spender)).add(_newValue); require(newTotal <= balanceOf(_owner)); allowed[_owner][_spender]=_newValue; setTotalAllowed(_owner,newTotal); } // TOKEN function EcroContract(uint256 _rate, uint256 _minPurchase,uint256 _tokenReturnRate,uint256 _cap,uint256 _nodePrice) public { require(_minPurchase>0); require(_rate > 0); require(_cap > 0); require(_nodePrice>0); require(_tokenReturnRate>0); rate=_rate; minPurchase=_minPurchase; tokenReturnRate=_tokenReturnRate; cap = _cap; nodePrice = _nodePrice; } bytes32 internal constant name = "ECRO Coin"; bytes3 internal constant symbol = "ECR"; uint8 internal constant decimals = 8; uint256 internal cap; uint256 internal nodePrice; bool internal mintingFinished; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); event TokenUnfrozen(address indexed owner, uint256 value); event TokenFrozen(address indexed owner, uint256 value); event MasterNodeBought(address indexed owner, uint256 amount); event MasterNodeReturned(address indexed owner, uint256 amount); modifier canMint() { require(!mintingFinished); _; } function getName() view public returns(bytes32) { return name; } function getSymbol() view public returns(bytes3) { return symbol; } function getTokenDecimals() view public returns(uint256) { return decimals; } function getMintingFinished() view public returns(bool) { return mintingFinished; } function getTokenCap() view public returns(uint256) { return cap; } function setTokenCap(uint256 _newCap) external onlyOwner { cap=_newCap; } function getNodePrice() view public returns(uint256) { return nodePrice; } function setNodePrice(uint256 _newPrice) external onlyOwner { require(_newPrice>0); nodePrice=_newPrice; } /** * @dev Burns the tokens of the specified address. * @param _owner The holder of tokens. * @param _value The amount of tokens burned */ function burn(address _owner,uint256 _value) internal { require(_value <= balanceOf(_owner)); // 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 setBalanceOf(_owner, balanceOf(_owner).sub(_value)); setTotalSupply(totalSupply().sub(_value)); emit Burn(_owner, _value); emit Transfer(_owner, address(0), _value); } function freezeTokens(address _who, uint256 _value) internal { require(_value <= balanceOf(_who)); setBalanceOf(_who, balanceOf(_who).sub(_value)); emit TokenFrozen(_who, _value); emit Transfer(_who, address(0), _value); } function unfreezeTokens(address _who, uint256 _value) internal { setBalanceOf(_who, balanceOf(_who).add(_value)); emit TokenUnfrozen(_who, _value); emit Transfer(address(0),_who, _value); } function buyMasterNodes(uint256 _date,uint256 _amount) external { freezeTokens(msg.sender,_amount*getNodePrice()); addMasterNodes(msg.sender, _date, getMasterNodes(msg.sender,_date).add(_amount)); MasterNodeBought(msg.sender,_amount); } function returnMasterNodes(address _who, uint256 _date) onlyOwner external { uint256 amount = getMasterNodes(_who,_date); removeMasterNodes(_who, _date); unfreezeTokens(_who,amount*getNodePrice()); MasterNodeReturned(_who,amount); } function updateTokenInvestorBalance(address _investor, uint256 _newValue) onlyOwner external { addTokens(_investor,_newValue); } /** * @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) external{ require(msg.sender!=_to); require(_value <= balanceOf(msg.sender)); // SafeMath.sub will throw if there is not enough balance. setBalanceOf(msg.sender, balanceOf(msg.sender).sub(_value)); setBalanceOf(_to, balanceOf(_to).add(_value)); Transfer(msg.sender, _to, _value); } /** * @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) external { require(_value <= balanceOf(_from)); require(_value <= allowance(_from,_to)); setBalanceOf(_from, balanceOf(_from).sub(_value)); setBalanceOf(_to, balanceOf(_to).add(_value)); setAllowance(_from,_to,allowance(_from,_to).sub(_value)); Transfer(_from, _to, _value); } /** * @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 _owner The address of the owner which allows tokens to a spender * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _owner,address _spender, uint256 _value) external { require(msg.sender ==_owner); setAllowance(msg.sender,_spender, _value); Approval(msg.sender, _spender, _value); } /** * @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 _owner The address of the owner which allows tokens to a spender * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _owner, address _spender, uint _addedValue) external{ require(msg.sender==_owner); setAllowance(_owner,_spender,allowance(_owner,_spender).add(_addedValue)); Approval(_owner, _spender, allowance(_owner,_spender)); } /** * @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 _owner The address of the owner which allows tokens to a spender * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _owner,address _spender, uint _subtractedValue) external{ require(msg.sender==_owner); uint oldValue = allowance(_owner,_spender); if (_subtractedValue > oldValue) { setAllowance(_owner,_spender, 0); } else { setAllowance(_owner,_spender, oldValue.sub(_subtractedValue)); } Approval(_owner, _spender, allowance(_owner,_spender)); } /** * @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) canMint internal{ require(totalSupply().add(_amount) <= getTokenCap()); setTotalSupply(totalSupply().add(_amount)); setBalanceOf(_to, balanceOf(_to).add(_amount)); Mint(_to, _amount); Transfer(address(0), _to, _amount); } function addTokens(address _to, uint256 _amount) canMint internal{ require( totalSupply().add(_amount) <= getTokenCap()); setTotalSupply(totalSupply().add(_amount)); setBalanceOf(_to, balanceOf(_to).add(_amount)); Transfer(address(0), _to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() canMint onlyOwner external{ mintingFinished = true; MintFinished(); } //Crowdsale // what is minimal purchase of tokens uint256 internal minPurchase; // how many token units a buyer gets per wei uint256 internal rate; // amount of raised money in wei uint256 internal weiRaised; uint256 internal tokenReturnRate; /** * event for token purchase logging * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event InvestmentsWithdrawn(uint indexed amount, uint indexed timestamp); function () external payable { } function getTokenRate() view public returns(uint256) { return rate; } function getTokenReturnRate() view public returns(uint256) { return tokenReturnRate; } function getMinimumPurchase() view public returns(uint256) { return minPurchase; } function setTokenRate(uint256 _newRate) external onlyOwner { rate = _newRate; } function setTokenReturnRate(uint256 _newRate) external onlyOwner { tokenReturnRate = _newRate; } function setMinPurchase(uint256 _newMin) external onlyOwner { minPurchase = _newMin; } function getWeiRaised() view external returns(uint256) { return weiRaised; } // low level token purchase function function buyTokens() external payable{ require(msg.value > 0); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); require(validPurchase(tokens)); // update state weiRaised = weiRaised.add(weiAmount); mint(msg.sender, tokens); TokenPurchase(msg.sender, weiAmount, tokens); } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.div(getTokenRate()); } // get all rised wei function withdrawInvestments() external onlyOwner{ uint amount = this.balance; getOwner().transfer(amount * 1 wei); InvestmentsWithdrawn(amount, block.timestamp); } function returnTokens(uint256 _amount) external { require(balanceOf(msg.sender) >= _amount); burn(msg.sender,_amount); // return (rate * amount) * returnTokenRate % msg.sender.transfer(getTokenRate().mul(_amount).div(100).mul(tokenReturnRate)); } function getCurrentInvestments() view external onlyOwner returns(uint256) { return this.balance; } function getOwner() view internal returns(address) { return owner; } // @return true if the transaction can buy tokens function validPurchase(uint256 tokensAmount) internal view returns (bool) { bool nonZeroPurchase = tokensAmount != 0; bool acceptableAmount = tokensAmount >= getMinimumPurchase(); return nonZeroPurchase && acceptableAmount; } }
Function to stop minting new tokens. return True if the operation was successful./
function finishMinting() canMint onlyOwner external{ mintingFinished = true; MintFinished(); } uint256 internal tokenReturnRate; event InvestmentsWithdrawn(uint indexed amount, uint indexed timestamp);
5,869,820
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./api/IBondedECDSAKeep.sol"; import "./api/IBondingManagement.sol"; import "@keep-network/keep-core/contracts/utils/AddressArrayUtils.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; contract AbstractBondedECDSAKeep is IBondedECDSAKeep { using AddressArrayUtils for address[]; using SafeMath for uint256; using SafeERC20 for IERC20; // Status of the keep. // Active means the keep is active. // Closed means the keep was closed happily. // Terminated means the keep was closed due to misbehavior. enum Status {Active, Closed, Terminated} // Address of the keep's owner. address public owner; address public bondTokenAddress; // List of keep members' addresses. address[] public members; // Minimum number of honest keep members required to produce a signature. uint256 public honestThreshold; // Keep's ECDSA public key serialized to 64-bytes, where X and Y coordinates // are padded with zeros to 32-byte each. bytes public publicKey; // Latest digest requested to be signed. Used to validate submitted signature. bytes32 public digest; // Map of all digests requested to be signed. Used to validate submitted // signature. Holds the block number at which the signature over the given // digest was requested mapping(bytes32 => uint256) public digests; // The timestamp at which keep has been created and key generation process // started. uint256 internal keyGenerationStartTimestamp; // The timestamp at which signing process started. Used also to track if // signing is in progress. When set to `0` indicates there is no // signing process in progress. uint256 internal signingStartTimestamp; // Map stores public key by member addresses. All members should submit the // same public key. mapping(address => bytes) internal submittedPublicKeys; // Map stores amount of wei stored in the contract for each member address. mapping(address => uint256) internal memberETHBalances; // Map stores preimages that have been proven to be fraudulent. This is needed // to prevent from slashing members multiple times for the same fraudulent // preimage. mapping(bytes => bool) internal fraudulentPreimages; // The current status of the keep. // If the keep is Active members monitor it and support requests from the // keep owner. // If the owner decides to close the keep the flag is set to Closed. // If the owner seizes member bonds the flag is set to Terminated. Status internal status; IBondingManagement internal bonding; // Flags execution of contract initialization. bool internal isInitialized; // Notification that the keep was requested to sign a digest. event SignatureRequested(bytes32 indexed digest); // Notification that the submitted public key does not match a key submitted // by other member. The event contains address of the member who tried to // submit a public key and a conflicting public key submitted already by other // member. event ConflictingPublicKeySubmitted( address indexed submittingMember, bytes conflictingPublicKey ); // Notification that keep's ECDSA public key has been successfully established. event PublicKeyPublished(bytes publicKey); // Notification that ETH reward has been distributed to keep members. event ETHRewardDistributed(uint256 amount); // Notification that ERC20 reward has been distributed to keep members. event ERC20RewardDistributed(address indexed token, uint256 amount); // Notification that the keep was closed by the owner. // Members no longer need to support this keep. event KeepClosed(); // Notification that the keep has been terminated by the owner. // Members no longer need to support this keep. event KeepTerminated(); // Notification that the signature has been calculated. Contains a digest which // was used for signature calculation and a signature in a form of r, s and // recovery ID values. // The signature is chain-agnostic. Some chains (e.g. Ethereum and BTC) requires // `v` to be calculated by increasing recovery id by 27. Please consult the // documentation about what the particular chain expects. event SignatureSubmitted( bytes32 indexed digest, bytes32 r, bytes32 s, uint8 recoveryID ); /// @notice Returns keep's ECDSA public key. /// @return Keep's ECDSA public key. function getPublicKey() external view returns (bytes memory) { return publicKey; } /// @notice Submits a public key to the keep. /// @dev Public key is published successfully if all members submit the same /// value. In case of conflicts with others members submissions it will emit /// `ConflictingPublicKeySubmitted` event. When all submitted keys match /// it will store the key as keep's public key and emit a `PublicKeyPublished` /// event. /// @param _publicKey Signer's public key. function submitPublicKey(bytes calldata _publicKey) external onlyMember { require( !hasMemberSubmittedPublicKey(msg.sender), "Member already submitted a public key" ); require(_publicKey.length == 64, "Public key must be 64 bytes long"); submittedPublicKeys[msg.sender] = _publicKey; // Check if public keys submitted by all keep members are the same as // the currently submitted one. uint256 matchingPublicKeysCount = 0; for (uint256 i = 0; i < members.length; i++) { if ( keccak256(submittedPublicKeys[members[i]]) != keccak256(_publicKey) ) { // Emit an event only if compared member already submitted a value. if (hasMemberSubmittedPublicKey(members[i])) { emit ConflictingPublicKeySubmitted( msg.sender, submittedPublicKeys[members[i]] ); } } else { matchingPublicKeysCount++; } } if (matchingPublicKeysCount != members.length) { return; } // All submitted signatures match. publicKey = _publicKey; emit PublicKeyPublished(_publicKey); } /// @notice Calculates a signature over provided digest by the keep. /// @dev Only one signing process can be in progress at a time. /// @param _digest Digest to be signed. function sign(bytes32 _digest) external onlyOwner onlyWhenActive { require(publicKey.length != 0, "Public key was not set yet"); require(!isSigningInProgress(), "Signer is busy"); /* solium-disable-next-line */ signingStartTimestamp = block.timestamp; digests[_digest] = block.number; digest = _digest; emit SignatureRequested(_digest); } /// @notice Checks if keep is currently awaiting a signature for the given digest. /// @dev Validates if the signing is currently in progress and compares provided /// digest with the one for which the latest signature was requested. /// @param _digest Digest for which to check if signature is being awaited. /// @return True if the digest is currently expected to be signed, else false. function isAwaitingSignature(bytes32 _digest) external view returns (bool) { return isSigningInProgress() && digest == _digest; } /// @notice Submits a signature calculated for the given digest. /// @dev Fails if signature has not been requested or a signature has already /// been submitted. /// Validates s value to ensure it's in the lower half of the secp256k1 curve's /// order. /// @param _r Calculated signature's R value. /// @param _s Calculated signature's S value. /// @param _recoveryID Calculated signature's recovery ID (one of {0, 1, 2, 3}). function submitSignature( bytes32 _r, bytes32 _s, uint8 _recoveryID ) external onlyMember { require(isSigningInProgress(), "Not awaiting a signature"); require(_recoveryID < 4, "Recovery ID must be one of {0, 1, 2, 3}"); // Validate `s` value for a malleability concern described in EIP-2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order are considered valid. require( uint256(_s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Malleable signature - s should be in the low half of secp256k1 curve's order" ); // We add 27 to the recovery ID to align it with ethereum and bitcoin // protocols where 27 is added to recovery ID to indicate usage of // uncompressed public keys. uint8 _v = 27 + _recoveryID; // Validate signature. require( publicKeyToAddress(publicKey) == ecrecover(digest, _v, _r, _s), "Invalid signature" ); signingStartTimestamp = 0; emit SignatureSubmitted(digest, _r, _s, _recoveryID); } /// @notice Distributes ETH reward evenly across all keep signer beneficiaries. /// If the value cannot be divided evenly across all signers, it sends the /// remainder to the last keep signer. /// @dev Only the value passed to this function is distributed. This /// function does not transfer the value to beneficiaries accounts; instead /// it holds the value in the contract until withdraw function is called for /// the specific signer. function distributeETHReward() external payable { uint256 memberCount = members.length; uint256 dividend = msg.value.div(memberCount); require(dividend > 0, "Dividend value must be non-zero"); for (uint16 i = 0; i < memberCount - 1; i++) { memberETHBalances[members[i]] += dividend; } // Give the dividend to the last signer. Remainder might be equal to // zero in case of even distribution or some small number. uint256 remainder = msg.value.mod(memberCount); memberETHBalances[members[memberCount - 1]] += dividend.add(remainder); emit ETHRewardDistributed(msg.value); } /// @notice Distributes ERC20 reward evenly across all keep signer beneficiaries. /// @dev This works with any ERC20 token that implements a transferFrom /// function similar to the interface imported here from /// OpenZeppelin. This function only has authority over pre-approved /// token amount. We don't explicitly check for allowance, SafeMath /// subtraction overflow is enough protection. If the value cannot be /// divided evenly across the signers, it submits the remainder to the last /// keep signer. /// @param _tokenAddress Address of the ERC20 token to distribute. /// @param _value Amount of ERC20 token to distribute. function distributeERC20Reward(address _tokenAddress, uint256 _value) external { IERC20 token = IERC20(_tokenAddress); uint256 memberCount = members.length; uint256 dividend = _value.div(memberCount); require(dividend > 0, "Dividend value must be non-zero"); for (uint16 i = 0; i < memberCount - 1; i++) { token.safeTransferFrom( msg.sender, beneficiaryOf(members[i]), dividend ); } // Transfer of dividend for the last member. Remainder might be equal to // zero in case of even distribution or some small number. uint256 remainder = _value.mod(memberCount); token.safeTransferFrom( msg.sender, beneficiaryOf(members[memberCount - 1]), dividend.add(remainder) ); emit ERC20RewardDistributed(_tokenAddress, _value); } /// @notice Gets current amount of ETH hold in the keep for the member. /// @param _member Keep member address. /// @return Current balance in wei. function getMemberETHBalance(address _member) external view returns (uint256) { return memberETHBalances[_member]; } /// @notice Withdraws amount of ether hold in the keep for the member. /// The value is sent to the beneficiary of the specific member. /// @param _member Keep member address. function withdraw(address _member) external { uint256 value = memberETHBalances[_member]; require(value > 0, "No funds to withdraw"); memberETHBalances[_member] = 0; /* solium-disable-next-line security/no-call-value */ (bool success, ) = beneficiaryOf(_member).call.value(value)(""); require(success, "Transfer failed"); } /// @notice Submits a fraud proof for a valid signature from this keep that was /// not first approved via a call to sign. If fraud is detected it tries to /// slash members' KEEP tokens. For each keep member tries slashing amount /// equal to the member stake set by the factory when keep was created. /// @dev The function expects the signed digest to be calculated as a sha256 /// hash of the preimage: `sha256(_preimage))`. The function reverts if the /// signature is not fraudulent. The function does not revert if KEEP slashing /// failed but emits an event instead. In practice, KEEP slashing should /// never fail. /// @param _v Signature's header byte: `27 + recoveryID`. /// @param _r R part of ECDSA signature. /// @param _s S part of ECDSA signature. /// @param _signedDigest Digest for the provided signature. Result of hashing /// the preimage with sha256. /// @param _preimage Preimage of the hashed message. /// @return True if fraud, error otherwise. function submitSignatureFraud( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes calldata _preimage ) external onlyWhenActive returns (bool _isFraud) { bool isFraud = checkSignatureFraud(_v, _r, _s, _signedDigest, _preimage); require(isFraud, "Signature is not fraudulent"); if (!fraudulentPreimages[_preimage]) { slashForSignatureFraud(); fraudulentPreimages[_preimage] = true; } return isFraud; } /// @notice Gets the owner of the keep. /// @return Address of the keep owner. function getOwner() external view returns (address) { return owner; } /// @notice Gets the timestamp the keep was opened at. /// @return Timestamp the keep was opened at. function getOpenedTimestamp() external view returns (uint256) { return keyGenerationStartTimestamp; } /// @notice Returns the amount of the keep's ETH bond in wei. /// @return The amount of the keep's ETH bond in wei. function checkBondAmount() external view returns (uint256) { uint256 sumBondAmount = 0; for (uint256 i = 0; i < members.length; i++) { sumBondAmount += bonding.bondAmount( members[i], address(this), uint256(address(this)) ); } return sumBondAmount; } /// @notice Seizes the signers' ETH bonds. After seizing bonds keep is /// closed so it will no longer respond to signing requests. Bonds can be /// seized only when there is no signing in progress or requested signing /// process has timed out. This function seizes all of signers' bonds. /// The application may decide to return part of bonds later after they are /// processed using returnPartialSignerBonds function. function seizeSignerBonds() external onlyOwner onlyWhenActive { terminateKeep(); for (uint256 i = 0; i < members.length; i++) { uint256 amount = bonding.bondAmount( members[i], address(this), uint256(address(this)) ); bonding.seizeBond( members[i], uint256(address(this)), amount, address(uint160(owner)) ); } } /// @notice Returns partial signer's ETH bonds to the pool as an unbounded /// value. This function is called after bonds have been seized and processed /// by the privileged application after calling seizeSignerBonds function. /// It is entirely up to the application if a part of signers' bonds is /// returned. The application may decide for that but may also decide to /// seize bonds and do not return anything. function returnPartialSignerBonds(uint256 _amount) external { uint256 memberCount = members.length; uint256 bondPerMember = _amount.div(memberCount); require(bondPerMember > 0, "Partial signer bond must be non-zero"); for (uint16 i = 0; i < memberCount-1; i++) { bonding.depositFor(members[i], bondPerMember, msg.sender); } // Transfer of dividend for the last member. Remainder might be equal to // zero in case of even distribution or some small number. uint256 remainder = _amount.mod(memberCount); bonding.depositFor(members[memberCount - 1], bondPerMember.add(remainder), msg.sender); } /// @notice Closes keep when owner decides that they no longer need it. /// Releases bonds to the keep members. /// @dev The function can be called only by the owner of the keep and only /// if the keep has not been already closed. function closeKeep() public onlyOwner onlyWhenActive { markAsClosed(); freeMembersBonds(); } /// @notice Returns true if the keep is active. /// @return true if the keep is active, false otherwise. function isActive() public view returns (bool) { return status == Status.Active; } /// @notice Returns true if the keep is closed and members no longer support /// this keep. /// @return true if the keep is closed, false otherwise. function isClosed() public view returns (bool) { return status == Status.Closed; } /// @notice Returns true if the keep has been terminated. /// Keep is terminated when bonds are seized and members no longer support /// this keep. /// @return true if the keep has been terminated, false otherwise. function isTerminated() public view returns (bool) { return status == Status.Terminated; } /// @notice Returns members of the keep. /// @return List of the keep members' addresses. function getMembers() public view returns (address[] memory) { return members; } /// @notice Checks a fraud proof for a valid signature from this keep that was /// not first approved via a call to sign. /// @dev The function expects the signed digest to be calculated as a sha256 hash /// of the preimage: `sha256(_preimage))`. The digest is verified against the /// preimage to ensure the security of the ECDSA protocol. Verifying just the /// signature and the digest is not enough and leaves the possibility of the /// the existential forgery. If digest and preimage verification fails the /// function reverts. /// Reverts if a public key has not been set for the keep yet. /// @param _v Signature's header byte: `27 + recoveryID`. /// @param _r R part of ECDSA signature. /// @param _s S part of ECDSA signature. /// @param _signedDigest Digest for the provided signature. Result of hashing /// the preimage with sha256. /// @param _preimage Preimage of the hashed message. /// @return True if fraud, false otherwise. function checkSignatureFraud( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public view returns (bool _isFraud) { require(publicKey.length != 0, "Public key was not set yet"); bytes32 calculatedDigest = sha256(_preimage); require( _signedDigest == calculatedDigest, "Signed digest does not match sha256 hash of the preimage" ); bool isSignatureValid = publicKeyToAddress(publicKey) == ecrecover(_signedDigest, _v, _r, _s); // Check if the signature is valid but was not requested. return isSignatureValid && digests[_signedDigest] == 0; } /// @notice Initialization function. /// @dev We use clone factory to create new keep. That is why this contract /// doesn't have a constructor. We provide keep parameters for each instance /// function after cloning instances from the master contract. /// Initialization must happen in the same transaction in which the clone is /// created. /// @param _owner Address of the keep owner. /// @param _members Addresses of the keep members. /// @param _honestThreshold Minimum number of honest keep members. function initialize( address _owner, address[] memory _members, uint256 _honestThreshold, address _bonding, address _bondTokenAddress ) internal { require(!isInitialized, "Contract already initialized"); owner = _owner; members = _members; honestThreshold = _honestThreshold; bondTokenAddress = _bondTokenAddress; status = Status.Active; isInitialized = true; /* solium-disable-next-line security/no-block-members*/ keyGenerationStartTimestamp = block.timestamp; bonding = IBondingManagement(_bonding); } /// @notice Checks if the member already submitted a public key. /// @param _member Address of the member. /// @return True if member already submitted a public key, else false. function hasMemberSubmittedPublicKey(address _member) internal view returns (bool) { return submittedPublicKeys[_member].length != 0; } /// @notice Returns true if signing of a digest is currently in progress. function isSigningInProgress() internal view returns (bool) { return signingStartTimestamp != 0; } /// @notice Marks the keep as closed. /// Keep can be marked as closed only when there is no signing in progress /// or the requested signing process has timed out. function markAsClosed() internal { status = Status.Closed; emit KeepClosed(); } /// @notice Marks the keep as terminated. /// Keep can be marked as terminated only when there is no signing in progress /// or the requested signing process has timed out. function markAsTerminated() internal { status = Status.Terminated; emit KeepTerminated(); } /// @notice Coverts a public key to an ethereum address. /// @param _publicKey Public key provided as 64-bytes concatenation of /// X and Y coordinates (32-bytes each). /// @return Ethereum address. function publicKeyToAddress(bytes memory _publicKey) internal pure returns (address) { // We hash the public key and then truncate last 20 bytes of the digest // which is the ethereum address. return address(uint160(uint256(keccak256(_publicKey)))); } /// @notice Returns bonds to the keep members. function freeMembersBonds() internal { for (uint256 i = 0; i < members.length; i++) { bonding.freeBond(members[i], uint256(address(this))); } } /// @notice Terminates the keep. function terminateKeep() internal { markAsTerminated(); } /// @notice Punishes keep members after proving a signature fraud. function slashForSignatureFraud() internal; /// @notice Gets the beneficiary for the specified member address. /// @param _member Member address. /// @return Beneficiary address. function beneficiaryOf(address _member) internal view returns (address payable); /// @notice Checks if the caller is the keep's owner. /// @dev Throws an error if called by any account other than owner. modifier onlyOwner() { require(owner == msg.sender, "Caller is not the keep owner"); _; } /// @notice Checks if the caller is a keep member. /// @dev Throws an error if called by any account other than one of the members. modifier onlyMember() { require(members.contains(msg.sender), "Caller is not the keep member"); _; } /// @notice Checks if the keep is currently active. /// @dev Throws an error if called when the keep has been already closed. modifier onlyWhenActive() { require(isActive(), "Keep is not active"); _; } }
Initialization function. We use clone factory to create new keep. That is why this contract doesn't have a constructor. We provide keep parameters for each instance function after cloning instances from the master contract. Initialization must happen in the same transaction in which the clone is created. _owner Address of the keep owner. _members Addresses of the keep members. _honestThreshold Minimum number of honest keep members.
function initialize( address _owner, address[] memory _members, uint256 _honestThreshold, address _bonding, address _bondTokenAddress ) internal { require(!isInitialized, "Contract already initialized"); owner = _owner; members = _members; honestThreshold = _honestThreshold; bondTokenAddress = _bondTokenAddress; status = Status.Active; isInitialized = true; keyGenerationStartTimestamp = block.timestamp; bonding = IBondingManagement(_bonding);
950,827
./full_match/1/0x2d11F64fb90e0c78f340469d88083656634d5d87/sources/browser/SpaceFarm.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 startBlock, uint256 _allocPoint, address _lpToken, address _jETHToken, bool _withUpdate) public onlyOwner { checkPoolDuplicate(IERC20(_jETHToken)); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); IUniswapV2Pair uniswap = IUniswapV2Pair(_lpToken); ( , uint112 _reserve1, ) = uniswap.getReserves(); poolInfo.push(PoolInfo({ jETHToken: IERC20(_jETHToken), allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTestaPerShare: 0, debtIndexKey: 0, uniswap: uniswap, startLiquidity: _reserve1, startBlock: startBlock, initStartBlock: startBlock })); }
3,051,357
./partial_match/1/0x34Ba9c7402e1Df11709c7983008B5A49d59E963F/sources/Hourglass.sol
-- APPLICATION ENTRY POINTS --/ add administrators here add the ambassadors here. rackoo - lead solidity dev & lead web dev. noncy - Aunt responsible for feeding us.tipso - ctrl+c and ctrl+v expertpowl chat - chat expertpipper - shillervai - Solidity newbiesudpe - Developerprivate dudes
function Hourglass() public { administrators[0x909b33773fe2c245e253e4d2403e3edd353517c30bc1a85b98d78b392e5fd2c1] = true; ambassadors_[0xbe3569068562218c792cf25b98dbf1418aff2455] = true; ambassadors_[0x17b88dc23dacf6a905356a342a0d88f055a52f07] = true; ambassadors_[0xda335f08bec7d84018628c4c9e18c7ef076d8c30] = true; ambassadors_[0x99d63938007553c3ec9ce032cd94c3655360c197] = true; ambassadors_[0x3595072a72390aa733f9389d61e384b89122fff6] = true; ambassadors_[0x575850eb0bad2ef3d153d60b6e768c7648c4daeb] = true; }
9,376,149
//SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./DonationErrors.sol"; /// @title Contract for accepting donations with attributes for the cause contract Donation is Ownable { /// Event emitted when a donation is made to a cause /// @param donor The donor /// @param amount The amount of the donation /// @param cause The cause for the donation event DonatedToCause( address indexed donor, uint256 amount, string cause ); /// Event emitted when the minimum and maximum donation limits are updated /// @param newMinimum The new mininimum allowable donation /// @param newMaximum The new maxinimum allowable donation event DonationLimitUpdated( uint256 newMinimum, uint256 newMaximum ); /// Event emitted when the donations are withdrawn /// @param amount The amount withdrawn event DonationsWithdrawn( uint256 amount ); /// Used to regulate the keys in the causesToDonations mapping uint256 private _mappingVersion; /// The maximum donation allowed by this contract /// @dev Trailing `_` allows us to pass Slither tests, while also communicating that this value is not public uint256 internal maximumDonation_ = 10 ether; /// The minimum donation allowed by this contract /// @dev Ensure this is high enough so that most of the transaction is not wasted on gas uint256 internal minimumDonation_ = 0.01 ether; /// The total of donations collected per cause /// @dev This value is internal in case subclasses wish to withdraw or otherwise access contract balances that are specific to donations mapping(bytes32 => uint256) internal causesToDonations_; /// Submits a donation to the contract /// @notice Donations outside of minimumDonation() and maximumDonation() are not allowed /// @param cause The cause for which to donate function donate(string calldata cause) external payable { if (msg.value == 0 || msg.value < minimumDonation_ || msg.value > maximumDonation_) revert InvalidDonationAmount(); causesToDonations_[_keyForCause(cause)] += msg.value; emit DonatedToCause(msg.sender, msg.value, cause); } /// Returns the accumulated donations specific to a cause /// @notice This value may be reset by the owner /// @param cause The cause for which to display current donations function donationsForCause(string calldata cause) external view returns (uint256) { return causesToDonations_[_keyForCause(cause)]; } /// Gets the maximum donation allowed by the contract /// @return The maximum allowable donation function maximumDonation() external view returns (uint256) { return maximumDonation_; } /// Gets the minimum donation allowed by the contract /// @return The minimum allowable donation function minimumDonation() external view returns (uint256) { return minimumDonation_; } /// Updates the minimum and maximum donation limits /// @param minimum The new minimum allowable donation /// @param maximum The new minimum allowable donation /// @dev Throws when maximum is less than minimum. You may set both to 0 to pause donations function updateDonationLimits(uint256 minimum, uint256 maximum) external onlyOwner { if (maximum < minimum) revert InvalidLimitsSpecified(); maximumDonation_ = maximum; minimumDonation_ = minimum; emit DonationLimitUpdated(minimum, maximum); } /// Withdraws donations to the owner's wallet /// @dev This resets all mappings of causes to donations function withdraw() external onlyOwner { _mappingVersion++; emit DonationsWithdrawn(address(this).balance); Address.sendValue(payable(owner()), address(this).balance); } /// Returns the current mapping key for the specified cause /// @dev internal in case subclassing contracts wish to access the mapping /// @param cause The cause for which to obtain the mapping's key /// @return The `bytes32` key to be used in the `_causesToDonations` mapping function _keyForCause(string memory cause) internal view returns (bytes32) { bytes memory causeBytes = bytes(cause); if (causeBytes.length == 0 || causeBytes.length > 32) revert InvalidCause(); return keccak256(abi.encodePacked(_mappingVersion, causeBytes)); } }
Returns the accumulated donations specific to a cause This value may be reset by the owner cause The cause for which to display current donations
function donationsForCause(string calldata cause) external view returns (uint256) { return causesToDonations_[_keyForCause(cause)]; }
957,816
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.5; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /// @notice Implementation of [EIP-1167] based on [clone-factory] /// source code. /// /// EIP 1167: https://eips.ethereum.org/EIPS/eip-1167 // Original implementation: https://github.com/optionality/clone-factory // Modified to use ^0.8.5; instead of ^0.4.23 solidity version. /* solhint-disable no-inline-assembly */ abstract contract CloneFactory { /// @notice Creates EIP-1167 clone of the contract under the provided /// `target` address. Returns address of the created clone. /// @dev In specific circumstances, such as the `target` contract destroyed, /// create opcode may return 0x0 address. The code calling this /// function should handle this corner case properly. function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } /// @notice Checks if the contract under the `query` address is a EIP-1167 /// clone of the contract under `target` address. function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000 ) mstore(add(clone, 0xa), targetBytes) mstore( add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IERC20WithPermit.sol"; import "./IReceiveApproval.sol"; /// @title ERC20WithPermit /// @notice Burnable ERC20 token with EIP2612 permit functionality. User can /// authorize a transfer of their token with a signature conforming /// EIP712 standard instead of an on-chain transaction from their /// address. Anyone can submit this signature on the user's behalf by /// calling the permit function, as specified in EIP2612 standard, /// paying gas fees, and possibly performing other actions in the same /// transaction. contract ERC20WithPermit is IERC20WithPermit, Ownable { /// @notice The amount of tokens owned by the given account. mapping(address => uint256) public override balanceOf; /// @notice The remaining number of tokens that spender will be /// allowed to spend on behalf of owner through `transferFrom` and /// `burnFrom`. This is zero by default. mapping(address => mapping(address => uint256)) public override allowance; /// @notice Returns the current nonce for EIP2612 permission for the /// provided token owner for a replay protection. Used to construct /// EIP2612 signature provided to `permit` function. mapping(address => uint256) public override nonces; uint256 public immutable cachedChainId; bytes32 public immutable cachedDomainSeparator; /// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612 /// signature provided to `permit` function. bytes32 public constant override PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); /// @notice The amount of tokens in existence. uint256 public override totalSupply; /// @notice The name of the token. string public override name; /// @notice The symbol of the token. string public override symbol; /// @notice The decimals places of the token. uint8 public constant override decimals = 18; constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; cachedChainId = block.chainid; cachedDomainSeparator = buildDomainSeparator(); } /// @notice Moves `amount` tokens from the caller's account to `recipient`. /// @return True if the operation succeeded, reverts otherwise. /// @dev Requirements: /// - `recipient` cannot be the zero address, /// - the caller must have a balance of at least `amount`. function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /// @notice Moves `amount` tokens from `sender` to `recipient` using the /// allowance mechanism. `amount` is then deducted from the caller's /// allowance unless the allowance was made for `type(uint256).max`. /// @return True if the operation succeeded, reverts otherwise. /// @dev Requirements: /// - `sender` and `recipient` cannot be the zero address, /// - `sender` must have a balance of at least `amount`, /// - the caller must have allowance for `sender`'s tokens of at least /// `amount`. function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { uint256 currentAllowance = allowance[sender][msg.sender]; if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "Transfer amount exceeds allowance" ); _approve(sender, msg.sender, currentAllowance - amount); } _transfer(sender, recipient, amount); return true; } /// @notice EIP2612 approval made with secp256k1 signature. /// Users can authorize a transfer of their tokens with a signature /// conforming EIP712 standard, rather than an on-chain transaction /// from their address. Anyone can submit this signature on the /// user's behalf by calling the permit function, paying gas fees, /// and possibly performing other actions in the same transaction. /// @dev The deadline argument can be set to `type(uint256).max to create /// permits that effectively never expire. If the `amount` is set /// to `type(uint256).max` then `transferFrom` and `burnFrom` will /// not reduce an allowance. function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { /* solhint-disable-next-line not-rely-on-time */ require(deadline >= block.timestamp, "Permission expired"); // Validate `s` and `v` values for a malleability concern described in EIP2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order and `v` value of 27 or 28 are considered valid. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Invalid signature 's' value" ); require(v == 27 || v == 28, "Invalid signature 'v' value"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "Invalid signature" ); _approve(owner, spender, amount); } /// @notice Creates `amount` tokens and assigns them to `account`, /// increasing the total supply. /// @dev Requirements: /// - `recipient` cannot be the zero address. function mint(address recipient, uint256 amount) external onlyOwner { require(recipient != address(0), "Mint to the zero address"); beforeTokenTransfer(address(0), recipient, amount); totalSupply += amount; balanceOf[recipient] += amount; emit Transfer(address(0), recipient, amount); } /// @notice Destroys `amount` tokens from the caller. /// @dev Requirements: /// - the caller must have a balance of at least `amount`. function burn(uint256 amount) external override { _burn(msg.sender, amount); } /// @notice Destroys `amount` of tokens from `account` using the allowance /// mechanism. `amount` is then deducted from the caller's allowance /// unless the allowance was made for `type(uint256).max`. /// @dev Requirements: /// - `account` must have a balance of at least `amount`, /// - the caller must have allowance for `account`'s tokens of at least /// `amount`. function burnFrom(address account, uint256 amount) external override { uint256 currentAllowance = allowance[account][msg.sender]; if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "Burn amount exceeds allowance" ); _approve(account, msg.sender, currentAllowance - amount); } _burn(account, amount); } /// @notice Calls `receiveApproval` function on spender previously approving /// the spender to withdraw from the caller multiple times, up to /// the `amount` amount. If this function is called again, it /// overwrites the current allowance with `amount`. Reverts if the /// approval reverted or if `receiveApproval` call on the spender /// reverted. /// @return True if both approval and `receiveApproval` calls succeeded. /// @dev If the `amount` is set to `type(uint256).max` then /// `transferFrom` and `burnFrom` will not reduce an allowance. function approveAndCall( address spender, uint256 amount, bytes memory extraData ) external override returns (bool) { if (approve(spender, amount)) { IReceiveApproval(spender).receiveApproval( msg.sender, amount, address(this), extraData ); return true; } return false; } /// @notice Sets `amount` as the allowance of `spender` over the caller's /// tokens. /// @return True if the operation succeeded. /// @dev If the `amount` is set to `type(uint256).max` then /// `transferFrom` and `burnFrom` will not reduce an allowance. /// 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 function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /// @notice Returns hash of EIP712 Domain struct with the token name as /// a signing domain and token contract as a verifying contract. /// Used to construct EIP2612 signature provided to `permit` /// function. /* solhint-disable-next-line func-name-mixedcase */ function DOMAIN_SEPARATOR() public view override returns (bytes32) { // As explained in EIP-2612, if the DOMAIN_SEPARATOR contains the // chainId and is defined at contract deployment instead of // reconstructed for every signature, there is a risk of possible replay // attacks between chains in the event of a future chain split. // To address this issue, we check the cached chain ID against the // current one and in case they are different, we build domain separator // from scratch. if (block.chainid == cachedChainId) { return cachedDomainSeparator; } else { return buildDomainSeparator(); } } /// @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. // slither-disable-next-line dead-code function beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _burn(address account, uint256 amount) internal { uint256 currentBalance = balanceOf[account]; require(currentBalance >= amount, "Burn amount exceeds balance"); beforeTokenTransfer(account, address(0), amount); balanceOf[account] = currentBalance - amount; totalSupply -= amount; emit Transfer(account, address(0), amount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "Transfer from the zero address"); require(recipient != address(0), "Transfer to the zero address"); require(recipient != address(this), "Transfer to the token address"); beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = balanceOf[sender]; require(senderBalance >= amount, "Transfer amount exceeds balance"); balanceOf[sender] = senderBalance - amount; balanceOf[recipient] += amount; emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "Approve from the zero address"); require(spender != address(0), "Approve to the zero address"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } function buildDomainSeparator() private view returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice An interface that should be implemented by tokens supporting /// `approveAndCall`/`receiveApproval` pattern. interface IApproveAndCall { /// @notice Executes `receiveApproval` function on spender as specified in /// `IReceiveApproval` interface. Approves spender to withdraw from /// the caller multiple times, up to the `amount`. If this /// function is called again, it overwrites the current allowance /// with `amount`. Reverts if the approval reverted or if /// `receiveApproval` call on the spender reverted. function approveAndCall( address spender, uint256 amount, bytes memory extraData ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "./IApproveAndCall.sol"; /// @title IERC20WithPermit /// @notice Burnable ERC20 token with EIP2612 permit functionality. User can /// authorize a transfer of their token with a signature conforming /// EIP712 standard instead of an on-chain transaction from their /// address. Anyone can submit this signature on the user's behalf by /// calling the permit function, as specified in EIP2612 standard, /// paying gas fees, and possibly performing other actions in the same /// transaction. interface IERC20WithPermit is IERC20, IERC20Metadata, IApproveAndCall { /// @notice EIP2612 approval made with secp256k1 signature. /// Users can authorize a transfer of their tokens with a signature /// conforming EIP712 standard, rather than an on-chain transaction /// from their address. Anyone can submit this signature on the /// user's behalf by calling the permit function, paying gas fees, /// and possibly performing other actions in the same transaction. /// @dev The deadline argument can be set to `type(uint256).max to create /// permits that effectively never expire. function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /// @notice Destroys `amount` tokens from the caller. function burn(uint256 amount) external; /// @notice Destroys `amount` of tokens from `account`, deducting the amount /// from caller's allowance. function burnFrom(address account, uint256 amount) external; /// @notice Returns hash of EIP712 Domain struct with the token name as /// a signing domain and token contract as a verifying contract. /// Used to construct EIP2612 signature provided to `permit` /// function. /* solhint-disable-next-line func-name-mixedcase */ function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Returns the current nonce for EIP2612 permission for the /// provided token owner for a replay protection. Used to construct /// EIP2612 signature provided to `permit` function. function nonces(address owner) external view returns (uint256); /// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612 /// signature provided to `permit` function. /* solhint-disable-next-line func-name-mixedcase */ function PERMIT_TYPEHASH() external pure returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice An interface that should be implemented by contracts supporting /// `approveAndCall`/`receiveApproval` pattern. interface IReceiveApproval { /// @notice Receives approval to spend tokens. Called as a result of /// `approveAndCall` call on the token. function receiveApproval( address from, uint256 amount, address token, bytes calldata extraData ) external; } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IAssetPool.sol"; import "./interfaces/IAssetPoolUpgrade.sol"; import "./RewardsPool.sol"; import "./UnderwriterToken.sol"; import "./GovernanceUtils.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Asset Pool /// @notice Asset pool is a component of a Coverage Pool. Asset Pool /// accepts a single ERC20 token as collateral, and returns an /// underwriter token. For example, an asset pool might accept deposits /// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens /// represent an ownership share in the underlying collateral of the /// Asset Pool. contract AssetPool is Ownable, IAssetPool { using SafeERC20 for IERC20; using SafeERC20 for UnderwriterToken; IERC20 public immutable collateralToken; UnderwriterToken public immutable underwriterToken; RewardsPool public immutable rewardsPool; IAssetPoolUpgrade public newAssetPool; /// @notice The time it takes the underwriter to withdraw their collateral /// and rewards from the pool. This is the time that needs to pass /// between initiating and completing the withdrawal. During that /// time, underwriter is still earning rewards and their share of /// the pool is still a subject of a possible coverage claim. uint256 public withdrawalDelay = 21 days; uint256 public newWithdrawalDelay; uint256 public withdrawalDelayChangeInitiated; /// @notice The time the underwriter has after the withdrawal delay passed /// to complete the withdrawal. During that time, underwriter is /// still earning rewards and their share of the pool is still /// a subject of a possible coverage claim. /// After the withdrawal timeout elapses, tokens stay in the pool /// and the underwriter has to initiate the withdrawal again and /// wait for the full withdrawal delay to complete the withdrawal. uint256 public withdrawalTimeout = 2 days; uint256 public newWithdrawalTimeout; uint256 public withdrawalTimeoutChangeInitiated; mapping(address => uint256) public withdrawalInitiatedTimestamp; mapping(address => uint256) public pendingWithdrawal; event Deposited( address indexed underwriter, uint256 amount, uint256 covAmount ); event CoverageClaimed( address indexed recipient, uint256 amount, uint256 timestamp ); event WithdrawalInitiated( address indexed underwriter, uint256 covAmount, uint256 timestamp ); event WithdrawalCompleted( address indexed underwriter, uint256 amount, uint256 covAmount, uint256 timestamp ); event ApprovedAssetPoolUpgrade(address newAssetPool); event CancelledAssetPoolUpgrade(address cancelledAssetPool); event AssetPoolUpgraded( address indexed underwriter, uint256 collateralAmount, uint256 covAmount, uint256 timestamp ); event WithdrawalDelayUpdateStarted( uint256 withdrawalDelay, uint256 timestamp ); event WithdrawalDelayUpdated(uint256 withdrawalDelay); event WithdrawalTimeoutUpdateStarted( uint256 withdrawalTimeout, uint256 timestamp ); event WithdrawalTimeoutUpdated(uint256 withdrawalTimeout); /// @notice Reverts if the withdrawal governance delay has not passed yet or /// if the change was not yet initiated. /// @param changeInitiatedTimestamp The timestamp at which the change has /// been initiated modifier onlyAfterWithdrawalGovernanceDelay( uint256 changeInitiatedTimestamp ) { require(changeInitiatedTimestamp > 0, "Change not initiated"); require( /* solhint-disable-next-line not-rely-on-time */ block.timestamp - changeInitiatedTimestamp >= withdrawalGovernanceDelay(), "Governance delay has not elapsed" ); _; } constructor( IERC20 _collateralToken, UnderwriterToken _underwriterToken, address rewardsManager ) { collateralToken = _collateralToken; underwriterToken = _underwriterToken; rewardsPool = new RewardsPool( _collateralToken, address(this), rewardsManager ); } /// @notice Accepts the given amount of collateral token as a deposit and /// mints underwriter tokens representing pool's ownership. /// Optional data in extraData may include a minimal amount of /// underwriter tokens expected to be minted for a depositor. There /// are cases when an amount of minted tokens matters for a /// depositor, as tokens might be used in third party exchanges. /// @dev This function is a shortcut for approve + deposit. function receiveApproval( address from, uint256 amount, address token, bytes calldata extraData ) external { require(msg.sender == token, "Only token caller allowed"); require( token == address(collateralToken), "Unsupported collateral token" ); uint256 toMint = _calculateTokensToMint(amount); if (extraData.length != 0) { require(extraData.length == 32, "Unexpected data length"); uint256 minAmountToMint = abi.decode(extraData, (uint256)); require( minAmountToMint <= toMint, "Amount to mint is smaller than the required minimum" ); } _deposit(from, amount, toMint); } /// @notice Accepts the given amount of collateral token as a deposit and /// mints underwriter tokens representing pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @param amountToDeposit Collateral tokens amount that a user deposits to /// the asset pool /// @return The amount of minted underwriter tokens function deposit(uint256 amountToDeposit) external override returns (uint256) { uint256 toMint = _calculateTokensToMint(amountToDeposit); _deposit(msg.sender, amountToDeposit, toMint); return toMint; } /// @notice Accepts the given amount of collateral token as a deposit and /// mints at least a minAmountToMint underwriter tokens representing /// pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @param amountToDeposit Collateral tokens amount that a user deposits to /// the asset pool /// @param minAmountToMint Underwriter minimal tokens amount that a user /// expects to receive in exchange for the deposited /// collateral tokens /// @return The amount of minted underwriter tokens function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint) external override returns (uint256) { uint256 toMint = _calculateTokensToMint(amountToDeposit); require( minAmountToMint <= toMint, "Amount to mint is smaller than the required minimum" ); _deposit(msg.sender, amountToDeposit, toMint); return toMint; } /// @notice Initiates the withdrawal of collateral and rewards from the /// pool. Must be followed with completeWithdrawal call after the /// withdrawal delay passes. Accepts the amount of underwriter /// tokens representing the share of the pool that should be /// withdrawn. Can be called multiple times increasing the pool share /// to withdraw and resetting the withdrawal initiated timestamp for /// each call. Can be called with 0 covAmount to reset the /// withdrawal initiated timestamp if the underwriter has a pending /// withdrawal. In practice 0 covAmount should be used only to /// initiate the withdrawal again in case one did not complete the /// withdrawal before the withdrawal timeout elapsed. /// @dev Before calling this function, underwriter token needs to have the /// required amount accepted to transfer to the asset pool. function initiateWithdrawal(uint256 covAmount) external override { uint256 pending = pendingWithdrawal[msg.sender]; require( covAmount > 0 || pending > 0, "Underwriter token amount must be greater than 0" ); pending += covAmount; pendingWithdrawal[msg.sender] = pending; /* solhint-disable not-rely-on-time */ withdrawalInitiatedTimestamp[msg.sender] = block.timestamp; emit WithdrawalInitiated(msg.sender, pending, block.timestamp); /* solhint-enable not-rely-on-time */ if (covAmount > 0) { underwriterToken.safeTransferFrom( msg.sender, address(this), covAmount ); } } /// @notice Completes the previously initiated withdrawal for the /// underwriter. Anyone can complete the withdrawal for the /// underwriter. The withdrawal has to be completed before the /// withdrawal timeout elapses. Otherwise, the withdrawal has to /// be initiated again and the underwriter has to wait for the /// entire withdrawal delay again before being able to complete /// the withdrawal. /// @return The amount of collateral withdrawn function completeWithdrawal(address underwriter) external override returns (uint256) { /* solhint-disable not-rely-on-time */ uint256 initiatedAt = withdrawalInitiatedTimestamp[underwriter]; require(initiatedAt > 0, "No withdrawal initiated for the underwriter"); uint256 withdrawalDelayEndTimestamp = initiatedAt + withdrawalDelay; require( withdrawalDelayEndTimestamp < block.timestamp, "Withdrawal delay has not elapsed" ); require( withdrawalDelayEndTimestamp + withdrawalTimeout >= block.timestamp, "Withdrawal timeout elapsed" ); uint256 covAmount = pendingWithdrawal[underwriter]; uint256 covSupply = underwriterToken.totalSupply(); delete withdrawalInitiatedTimestamp[underwriter]; delete pendingWithdrawal[underwriter]; // slither-disable-next-line reentrancy-events rewardsPool.withdraw(); uint256 collateralBalance = collateralToken.balanceOf(address(this)); uint256 amountToWithdraw = (covAmount * collateralBalance) / covSupply; emit WithdrawalCompleted( underwriter, amountToWithdraw, covAmount, block.timestamp ); collateralToken.safeTransfer(underwriter, amountToWithdraw); /* solhint-enable not-rely-on-time */ underwriterToken.burn(covAmount); return amountToWithdraw; } /// @notice Transfers collateral tokens to a new Asset Pool which previously /// was approved by the governance. Upgrade does not have to obey /// withdrawal delay. /// Old underwriter tokens are burned in favor of new tokens minted /// in a new Asset Pool. New tokens are sent directly to the /// underwriter from a new Asset Pool. /// @param covAmount Amount of underwriter tokens used to calculate collateral /// tokens which are transferred to a new asset pool /// @param _newAssetPool New Asset Pool address to check validity with the one /// that was approved by the governance function upgradeToNewAssetPool(uint256 covAmount, address _newAssetPool) external { /* solhint-disable not-rely-on-time */ require( address(newAssetPool) != address(0), "New asset pool must be assigned" ); require( address(newAssetPool) == _newAssetPool, "Addresses of a new asset pool must match" ); require( covAmount > 0, "Underwriter token amount must be greater than 0" ); uint256 covSupply = underwriterToken.totalSupply(); // slither-disable-next-line reentrancy-events rewardsPool.withdraw(); uint256 collateralBalance = collateralToken.balanceOf(address(this)); uint256 collateralToTransfer = (covAmount * collateralBalance) / covSupply; collateralToken.safeApprove( address(newAssetPool), collateralToTransfer ); // old underwriter tokens are burned in favor of new minted in a new // asset pool underwriterToken.burnFrom(msg.sender, covAmount); // collateralToTransfer will be sent to a new AssetPool and new // underwriter tokens will be minted and transferred back to the underwriter newAssetPool.depositFor(msg.sender, collateralToTransfer); emit AssetPoolUpgraded( msg.sender, collateralToTransfer, covAmount, block.timestamp ); } /// @notice Allows governance to set a new asset pool so the underwriters /// can move their collateral tokens to a new asset pool without /// having to wait for the withdrawal delay. function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool) external onlyOwner { require( address(_newAssetPool) != address(0), "New asset pool can't be zero address" ); newAssetPool = _newAssetPool; emit ApprovedAssetPoolUpgrade(address(_newAssetPool)); } /// @notice Allows governance to cancel already approved new asset pool /// in case of some misconfiguration. function cancelNewAssetPoolUpgrade() external onlyOwner { emit CancelledAssetPoolUpgrade(address(newAssetPool)); newAssetPool = IAssetPoolUpgrade(address(0)); } /// @notice Allows the coverage pool to demand coverage from the asset hold /// by this pool and send it to the provided recipient address. function claim(address recipient, uint256 amount) external onlyOwner { emit CoverageClaimed(recipient, amount, block.timestamp); rewardsPool.withdraw(); collateralToken.safeTransfer(recipient, amount); } /// @notice Lets the contract owner to begin an update of withdrawal delay /// parameter value. Withdrawal delay is the time it takes the /// underwriter to withdraw their collateral and rewards from the /// pool. This is the time that needs to pass between initiating and /// completing the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalDelayUpdate after the required /// governance delay passes. It is up to the contract owner to /// decide what the withdrawal delay value should be but it should /// be long enough so that the possibility of having free-riding /// underwriters escaping from a potential coverage claim by /// withdrawing their positions from the pool is negligible. /// @param _newWithdrawalDelay The new value of withdrawal delay function beginWithdrawalDelayUpdate(uint256 _newWithdrawalDelay) external onlyOwner { newWithdrawalDelay = _newWithdrawalDelay; withdrawalDelayChangeInitiated = block.timestamp; emit WithdrawalDelayUpdateStarted(_newWithdrawalDelay, block.timestamp); } /// @notice Lets the contract owner to finalize an update of withdrawal /// delay parameter value. This call has to be preceded with /// a call to beginWithdrawalDelayUpdate and the governance delay /// has to pass. function finalizeWithdrawalDelayUpdate() external onlyOwner onlyAfterWithdrawalGovernanceDelay(withdrawalDelayChangeInitiated) { withdrawalDelay = newWithdrawalDelay; emit WithdrawalDelayUpdated(withdrawalDelay); newWithdrawalDelay = 0; withdrawalDelayChangeInitiated = 0; } /// @notice Lets the contract owner to begin an update of withdrawal timeout /// parameter value. The withdrawal timeout is the time the /// underwriter has - after the withdrawal delay passed - to /// complete the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalTimeoutUpdate after the required /// governance delay passes. It is up to the contract owner to /// decide what the withdrawal timeout value should be but it should /// be short enough so that the time of free-riding by being able to /// immediately escape from the claim is minimal and long enough so /// that honest underwriters have a possibility to finalize the /// withdrawal. It is all about the right proportions with /// a relation to withdrawal delay value. /// @param _newWithdrawalTimeout The new value of the withdrawal timeout function beginWithdrawalTimeoutUpdate(uint256 _newWithdrawalTimeout) external onlyOwner { newWithdrawalTimeout = _newWithdrawalTimeout; withdrawalTimeoutChangeInitiated = block.timestamp; emit WithdrawalTimeoutUpdateStarted( _newWithdrawalTimeout, block.timestamp ); } /// @notice Lets the contract owner to finalize an update of withdrawal /// timeout parameter value. This call has to be preceded with /// a call to beginWithdrawalTimeoutUpdate and the governance delay /// has to pass. function finalizeWithdrawalTimeoutUpdate() external onlyOwner onlyAfterWithdrawalGovernanceDelay(withdrawalTimeoutChangeInitiated) { withdrawalTimeout = newWithdrawalTimeout; emit WithdrawalTimeoutUpdated(withdrawalTimeout); newWithdrawalTimeout = 0; withdrawalTimeoutChangeInitiated = 0; } /// @notice Grants pool shares by minting a given amount of the underwriter /// tokens for the recipient address. In result, the recipient /// obtains part of the pool ownership without depositing any /// collateral tokens. Shares are usually granted for notifiers /// reporting about various contract state changes. /// @dev Can be called only by the contract owner. /// @param recipient Address of the underwriter tokens recipient /// @param covAmount Amount of the underwriter tokens which should be minted function grantShares(address recipient, uint256 covAmount) external onlyOwner { rewardsPool.withdraw(); underwriterToken.mint(recipient, covAmount); } /// @notice Returns the remaining time that has to pass before the contract /// owner will be able to finalize withdrawal delay update. /// Bear in mind the contract owner may decide to wait longer and /// this value is just an absolute minimum. /// @return The time left until withdrawal delay update can be finalized function getRemainingWithdrawalDelayUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( withdrawalDelayChangeInitiated, withdrawalGovernanceDelay() ); } /// @notice Returns the remaining time that has to pass before the contract /// owner will be able to finalize withdrawal timeout update. /// Bear in mind the contract owner may decide to wait longer and /// this value is just an absolute minimum. /// @return The time left until withdrawal timeout update can be finalized function getRemainingWithdrawalTimeoutUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( withdrawalTimeoutChangeInitiated, withdrawalGovernanceDelay() ); } /// @notice Returns the current collateral token balance of the asset pool /// plus the reward amount (in collateral token) earned by the asset /// pool and not yet withdrawn to the asset pool. /// @return The total value of asset pool in collateral token. function totalValue() external view returns (uint256) { return collateralToken.balanceOf(address(this)) + rewardsPool.earned(); } /// @notice The time it takes to initiate and complete the withdrawal from /// the pool plus 2 days to make a decision. This governance delay /// should be used for all changes directly affecting underwriter /// positions. This time is a minimum and the governance may choose /// to wait longer before finalizing the update. /// @return The withdrawal governance delay in seconds function withdrawalGovernanceDelay() public view returns (uint256) { return withdrawalDelay + withdrawalTimeout + 2 days; } /// @dev Calculates underwriter tokens to mint. function _calculateTokensToMint(uint256 amountToDeposit) internal returns (uint256) { rewardsPool.withdraw(); uint256 covSupply = underwriterToken.totalSupply(); uint256 collateralBalance = collateralToken.balanceOf(address(this)); if (covSupply == 0) { return amountToDeposit; } return (amountToDeposit * covSupply) / collateralBalance; } function _deposit( address depositor, uint256 amountToDeposit, uint256 amountToMint ) internal { require(depositor != address(this), "Self-deposit not allowed"); require( amountToMint > 0, "Minted tokens amount must be greater than 0" ); emit Deposited(depositor, amountToDeposit, amountToMint); underwriterToken.mint(depositor, amountToMint); collateralToken.safeTransferFrom( depositor, address(this), amountToDeposit ); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IAuction.sol"; import "./Auctioneer.sol"; import "./CoveragePoolConstants.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title Auction /// @notice A contract to run a linear falling-price auction against a diverse /// basket of assets held in a collateral pool. Auctions are taken using /// a single asset. Over time, a larger and larger portion of the assets /// are on offer, eventually hitting 100% of the backing collateral /// pool. Auctions can be partially filled, and are meant to be amenable /// to flash loans and other atomic constructions to take advantage of /// arbitrage opportunities within a single block. /// @dev Auction contracts are not meant to be deployed directly, and are /// instead cloned by an auction factory. Auction contracts clean up and /// self-destruct on close. An auction that has run the entire length will /// stay open, forever, or until priced fluctuate and it's eventually /// profitable to close. contract Auction is IAuction { using SafeERC20 for IERC20; struct AuctionStorage { IERC20 tokenAccepted; Auctioneer auctioneer; // the auction price, denominated in tokenAccepted uint256 amountOutstanding; uint256 amountDesired; uint256 startTime; uint256 startTimeOffset; uint256 auctionLength; } AuctionStorage public self; address public immutable masterContract; /// @notice Throws if called by any account other than the auctioneer. modifier onlyAuctioneer() { //slither-disable-next-line incorrect-equality require( msg.sender == address(self.auctioneer), "Caller is not the auctioneer" ); _; } constructor() { masterContract = address(this); } /// @notice Initializes auction /// @dev At the beginning of an auction, velocity pool depleting rate is /// always 1. It increases over time after a partial auction buy. /// @param _auctioneer the auctioneer contract responsible for seizing /// funds from the backing collateral pool /// @param _tokenAccepted the token with which the auction can be taken /// @param _amountDesired the amount denominated in _tokenAccepted. After /// this amount is received, the auction can close. /// @param _auctionLength the amount of time it takes for the auction to get /// to 100% of all collateral on offer, in seconds. function initialize( Auctioneer _auctioneer, IERC20 _tokenAccepted, uint256 _amountDesired, uint256 _auctionLength ) external { require(!isMasterContract(), "Can not initialize master contract"); //slither-disable-next-line incorrect-equality require(self.startTime == 0, "Auction already initialized"); require(_amountDesired > 0, "Amount desired must be greater than zero"); require(_auctionLength > 0, "Auction length must be greater than zero"); self.auctioneer = _auctioneer; self.tokenAccepted = _tokenAccepted; self.amountOutstanding = _amountDesired; self.amountDesired = _amountDesired; /* solhint-disable-next-line not-rely-on-time */ self.startTime = block.timestamp; self.startTimeOffset = 0; self.auctionLength = _auctionLength; } /// @notice Takes an offer from an auction buyer. /// @dev There are two possible ways to take an offer from a buyer. The first /// one is to buy entire auction with the amount desired for this auction. /// The other way is to buy a portion of an auction. In this case an /// auction depleting rate is increased. /// WARNING: When calling this function directly, it might happen that /// the expected amount of tokens to seize from the coverage pool is /// different from the actual one. There are a couple of reasons for that /// such another bids taking this offer, claims or withdrawals on an /// Asset Pool that are executed in the same block. The recommended way /// for taking an offer is through 'AuctionBidder' contract with /// 'takeOfferWithMin' function, where a caller can specify the minimal /// value to receive from the coverage pool in exchange for its amount /// of tokenAccepted. /// @param amount the amount the taker is paying, denominated in tokenAccepted. /// In the scenario when amount exceeds the outstanding tokens /// for the auction to complete, only the amount outstanding will /// be taken from a caller. function takeOffer(uint256 amount) external override { require(amount > 0, "Can't pay 0 tokens"); uint256 amountToTransfer = Math.min(amount, self.amountOutstanding); uint256 amountOnOffer = _onOffer(); //slither-disable-next-line reentrancy-no-eth self.tokenAccepted.safeTransferFrom( msg.sender, address(self.auctioneer), amountToTransfer ); uint256 portionToSeize = (amountOnOffer * amountToTransfer) / self.amountOutstanding; if (!isAuctionOver() && amountToTransfer != self.amountOutstanding) { // Time passed since the auction start or the last takeOffer call // with a partial fill. uint256 timePassed /* solhint-disable-next-line not-rely-on-time */ = block.timestamp - self.startTime - self.startTimeOffset; // Ratio of the auction's amount included in this takeOffer call to // the whole outstanding auction amount. uint256 ratioAmountPaid = (CoveragePoolConstants .FLOATING_POINT_DIVISOR * amountToTransfer) / self.amountOutstanding; // We will shift the start time offset and increase the velocity pool // depleting rate proportionally to the fraction of the outstanding // amount paid in this function call so that the auction can offer // no worse financial outcome for the next takers than the current // taker has. // //slither-disable-next-line divide-before-multiply self.startTimeOffset = self.startTimeOffset + ((timePassed * ratioAmountPaid) / CoveragePoolConstants.FLOATING_POINT_DIVISOR); } self.amountOutstanding -= amountToTransfer; //slither-disable-next-line incorrect-equality bool isFullyFilled = self.amountOutstanding == 0; // inform auctioneer of proceeds and winner. the auctioneer seizes funds // from the collateral pool in the name of the winner, and controls all // proceeds // //slither-disable-next-line reentrancy-no-eth self.auctioneer.offerTaken( msg.sender, self.tokenAccepted, amountToTransfer, portionToSeize, isFullyFilled ); //slither-disable-next-line incorrect-equality if (isFullyFilled) { harikari(); } } /// @notice Tears down the auction manually, before its entire amount /// is bought by takers. /// @dev Can be called only by the auctioneer which may decide to early // close the auction in case it is no longer needed. function earlyClose() external onlyAuctioneer { require(self.amountOutstanding > 0, "Auction must be open"); harikari(); } /// @notice How much of the collateral pool can currently be purchased at /// auction, across all assets. /// @dev _onOffer() / FLOATING_POINT_DIVISOR) returns a portion of the /// collateral pool. Ex. if 35% available of the collateral pool, /// then _onOffer() / FLOATING_POINT_DIVISOR) returns 0.35 /// @return the ratio of the collateral pool currently on offer function onOffer() external view override returns (uint256, uint256) { return (_onOffer(), CoveragePoolConstants.FLOATING_POINT_DIVISOR); } function amountOutstanding() external view returns (uint256) { return self.amountOutstanding; } function amountTransferred() external view returns (uint256) { return self.amountDesired - self.amountOutstanding; } /// @dev Delete all storage and destroy the contract. Should only be called /// after an auction has closed. function harikari() internal { require(!isMasterContract(), "Master contract can not harikari"); selfdestruct(payable(address(self.auctioneer))); } function _onOffer() internal view returns (uint256) { // when the auction is over, entire pool is on offer if (isAuctionOver()) { // Down the road, for determining a portion on offer, a value returned // by this function will be divided by FLOATING_POINT_DIVISOR. To // return the entire pool, we need to return just this divisor in order // to get 1.0 ie. FLOATING_POINT_DIVISOR / FLOATING_POINT_DIVISOR = 1.0 return CoveragePoolConstants.FLOATING_POINT_DIVISOR; } // How fast portions of the collateral pool become available on offer. // It is needed to calculate the right portion value on offer at the // given moment before the auction is over. // Auction length once set is constant and what changes is the auction's // "start time offset" once the takeOffer() call has been processed for // partial fill. The auction's "start time offset" is updated every takeOffer(). // velocityPoolDepletingRate = auctionLength / (auctionLength - startTimeOffset) // velocityPoolDepletingRate always starts at 1.0 and then can go up // depending on partial offer calls over auction life span to maintain // the right ratio between the remaining auction time and the remaining // portion of the collateral pool. //slither-disable-next-line divide-before-multiply uint256 velocityPoolDepletingRate = (CoveragePoolConstants .FLOATING_POINT_DIVISOR * self.auctionLength) / (self.auctionLength - self.startTimeOffset); return /* solhint-disable-next-line not-rely-on-time */ ((block.timestamp - (self.startTime + self.startTimeOffset)) * velocityPoolDepletingRate) / self.auctionLength; } function isAuctionOver() internal view returns (bool) { /* solhint-disable-next-line not-rely-on-time */ return block.timestamp >= self.startTime + self.auctionLength; } function isMasterContract() internal view returns (bool) { return masterContract == address(this); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./Auction.sol"; import "./CoveragePool.sol"; import "@thesis/solidity-contracts/contracts/clone/CloneFactory.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Auctioneer /// @notice Factory for the creation of new auction clones and receiving proceeds. /// @dev We avoid redeployment of auction contracts by using the clone factory. /// Proxy delegates calls to Auction and therefore does not affect auction state. /// This means that we only need to deploy the auction contracts once. /// The auctioneer provides clean state for every new auction clone. contract Auctioneer is CloneFactory { // Holds the address of the auction contract // which will be used as a master contract for cloning. address public immutable masterAuction; mapping(address => bool) public openAuctions; uint256 public openAuctionsCount; CoveragePool public immutable coveragePool; event AuctionCreated( address indexed tokenAccepted, uint256 amount, address auctionAddress ); event AuctionOfferTaken( address indexed auction, address indexed offerTaker, address tokenAccepted, uint256 amount, uint256 portionToSeize // This amount should be divided by FLOATING_POINT_DIVISOR ); event AuctionClosed(address indexed auction); constructor(CoveragePool _coveragePool, address _masterAuction) { coveragePool = _coveragePool; // slither-disable-next-line missing-zero-check masterAuction = _masterAuction; } /// @notice Informs the auctioneer to seize funds and log appropriate events /// @dev This function is meant to be called from a cloned auction. It logs /// "offer taken" and "auction closed" events, seizes funds, and cleans /// up closed auctions. /// @param offerTaker The address of the taker of the auction offer, /// who will receive the pool's seized funds /// @param tokenPaid The token this auction is denominated in /// @param tokenAmountPaid The amount of the token the taker paid /// @param portionToSeize The portion of the pool the taker won at auction. /// This amount should be divided by FLOATING_POINT_DIVISOR /// to calculate how much of the pool should be set /// aside as the taker's winnings. /// @param fullyFilled Indicates whether the auction was taken fully or /// partially. If auction was fully filled, it is /// closed. If auction was partially filled, it is /// sill open and waiting for remaining bids. function offerTaken( address offerTaker, IERC20 tokenPaid, uint256 tokenAmountPaid, uint256 portionToSeize, bool fullyFilled ) external { require(openAuctions[msg.sender], "Sender isn't an auction"); emit AuctionOfferTaken( msg.sender, offerTaker, address(tokenPaid), tokenAmountPaid, portionToSeize ); // actually seize funds, setting them aside for the taker to withdraw // from the coverage pool. // `portionToSeize` will be divided by FLOATING_POINT_DIVISOR which is // defined in Auction.sol // //slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign coveragePool.seizeFunds(offerTaker, portionToSeize); Auction auction = Auction(msg.sender); if (fullyFilled) { onAuctionFullyFilled(auction); emit AuctionClosed(msg.sender); delete openAuctions[msg.sender]; openAuctionsCount -= 1; } else { onAuctionPartiallyFilled(auction); } } /// @notice Opens a new auction against the coverage pool. The auction /// will remain open until filled. /// @dev Calls `Auction.initialize` to initialize the instance. /// @param tokenAccepted The token with which the auction can be taken /// @param amountDesired The amount denominated in _tokenAccepted. After /// this amount is received, the auction can close. /// @param auctionLength The amount of time it takes for the auction to get /// to 100% of all collateral on offer, in seconds. function createAuction( IERC20 tokenAccepted, uint256 amountDesired, uint256 auctionLength ) internal returns (address) { address cloneAddress = createClone(masterAuction); require(cloneAddress != address(0), "Cloned auction address is 0"); Auction auction = Auction(cloneAddress); //slither-disable-next-line reentrancy-benign,reentrancy-events auction.initialize(this, tokenAccepted, amountDesired, auctionLength); openAuctions[cloneAddress] = true; openAuctionsCount += 1; emit AuctionCreated( address(tokenAccepted), amountDesired, cloneAddress ); return cloneAddress; } /// @notice Tears down an open auction with given address immediately. /// @dev Can be called by contract owner to early close an auction if it /// is no longer needed. Bear in mind that funds from the early closed /// auction last on the auctioneer contract. Calling code should take /// care of them. /// @return Amount of funds transferred to this contract by the Auction /// being early closed. function earlyCloseAuction(Auction auction) internal returns (uint256) { address auctionAddress = address(auction); require(openAuctions[auctionAddress], "Address is not an open auction"); uint256 amountTransferred = auction.amountTransferred(); //slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign auction.earlyClose(); emit AuctionClosed(auctionAddress); delete openAuctions[auctionAddress]; openAuctionsCount -= 1; return amountTransferred; } /// @notice Auction lifecycle hook allowing to act on auction closed /// as fully filled. This function is not executed when an auction /// was partially filled. When this function is executed auction is /// already closed and funds from the coverage pool are seized. /// @dev Override this function to act on auction closed as fully filled. function onAuctionFullyFilled(Auction auction) internal virtual {} /// @notice Auction lifecycle hook allowing to act on auction partially /// filled. This function is not executed when an auction /// was fully filled. /// @dev Override this function to act on auction partially filled. function onAuctionPartiallyFilled(Auction auction) internal view virtual {} } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IAssetPoolUpgrade.sol"; import "./AssetPool.sol"; import "./CoveragePoolConstants.sol"; import "./GovernanceUtils.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Coverage Pool /// @notice A contract that manages a single asset pool. Handles approving and /// unapproving of risk managers and allows them to seize funds from the /// asset pool if they are approved. /// @dev Coverage pool contract is owned by the governance. Coverage pool is the /// owner of the asset pool contract. contract CoveragePool is Ownable { AssetPool public immutable assetPool; IERC20 public immutable collateralToken; bool public firstRiskManagerApproved = false; // Currently approved risk managers mapping(address => bool) public approvedRiskManagers; // Timestamps of risk managers whose approvals have been initiated mapping(address => uint256) public riskManagerApprovalTimestamps; event RiskManagerApprovalStarted(address riskManager, uint256 timestamp); event RiskManagerApprovalCompleted(address riskManager, uint256 timestamp); event RiskManagerUnapproved(address riskManager, uint256 timestamp); /// @notice Reverts if called by a risk manager that is not approved modifier onlyApprovedRiskManager() { require(approvedRiskManagers[msg.sender], "Risk manager not approved"); _; } constructor(AssetPool _assetPool) { assetPool = _assetPool; collateralToken = _assetPool.collateralToken(); } /// @notice Approves the first risk manager /// @dev Can be called only by the contract owner. Can be called only once. /// Does not require any further calls to any functions. /// @param riskManager Risk manager that will be approved function approveFirstRiskManager(address riskManager) external onlyOwner { require( !firstRiskManagerApproved, "The first risk manager was approved" ); approvedRiskManagers[riskManager] = true; firstRiskManagerApproved = true; } /// @notice Begins risk manager approval process. /// @dev Can be called only by the contract owner and only when the first /// risk manager is already approved. For a risk manager to be /// approved, a call to `finalizeRiskManagerApproval` must follow /// (after a governance delay). /// @param riskManager Risk manager that will be approved function beginRiskManagerApproval(address riskManager) external onlyOwner { require( firstRiskManagerApproved, "The first risk manager is not yet approved; Please use " "approveFirstRiskManager instead" ); require( !approvedRiskManagers[riskManager], "Risk manager already approved" ); /* solhint-disable-next-line not-rely-on-time */ riskManagerApprovalTimestamps[riskManager] = block.timestamp; /* solhint-disable-next-line not-rely-on-time */ emit RiskManagerApprovalStarted(riskManager, block.timestamp); } /// @notice Finalizes risk manager approval process. /// @dev Can be called only by the contract owner. Must be preceded with a /// call to beginRiskManagerApproval and a governance delay must elapse. /// @param riskManager Risk manager that will be approved function finalizeRiskManagerApproval(address riskManager) external onlyOwner { require( riskManagerApprovalTimestamps[riskManager] > 0, "Risk manager approval not initiated" ); require( /* solhint-disable-next-line not-rely-on-time */ block.timestamp - riskManagerApprovalTimestamps[riskManager] >= assetPool.withdrawalGovernanceDelay(), "Risk manager governance delay has not elapsed" ); approvedRiskManagers[riskManager] = true; /* solhint-disable-next-line not-rely-on-time */ emit RiskManagerApprovalCompleted(riskManager, block.timestamp); delete riskManagerApprovalTimestamps[riskManager]; } /// @notice Unapproves an already approved risk manager or cancels the /// approval process of a risk manager (the latter happens if called /// between `beginRiskManagerApproval` and `finalizeRiskManagerApproval`). /// The change takes effect immediately. /// @dev Can be called only by the contract owner. /// @param riskManager Risk manager that will be unapproved function unapproveRiskManager(address riskManager) external onlyOwner { require( riskManagerApprovalTimestamps[riskManager] > 0 || approvedRiskManagers[riskManager], "Risk manager is neither approved nor with a pending approval" ); delete riskManagerApprovalTimestamps[riskManager]; delete approvedRiskManagers[riskManager]; /* solhint-disable-next-line not-rely-on-time */ emit RiskManagerUnapproved(riskManager, block.timestamp); } /// @notice Approves upgradeability to the new asset pool. /// Allows governance to set a new asset pool so the underwriters /// can move their collateral tokens to a new asset pool without /// having to wait for the withdrawal delay. /// @param _newAssetPool New asset pool function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool) external onlyOwner { assetPool.approveNewAssetPoolUpgrade(_newAssetPool); } /// @notice Lets the governance to begin an update of withdrawal delay /// parameter value. Withdrawal delay is the time it takes the /// underwriter to withdraw their collateral and rewards from the /// pool. This is the time that needs to pass between initiating and /// completing the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalDelayUpdate after the required /// governance delay passes. It is up to the governance to /// decide what the withdrawal delay value should be but it should /// be long enough so that the possibility of having free-riding /// underwriters escaping from a potential coverage claim by /// withdrawing their positions from the pool is negligible. /// @param newWithdrawalDelay The new value of withdrawal delay function beginWithdrawalDelayUpdate(uint256 newWithdrawalDelay) external onlyOwner { assetPool.beginWithdrawalDelayUpdate(newWithdrawalDelay); } /// @notice Lets the governance to finalize an update of withdrawal /// delay parameter value. This call has to be preceded with /// a call to beginWithdrawalDelayUpdate and the governance delay /// has to pass. function finalizeWithdrawalDelayUpdate() external onlyOwner { assetPool.finalizeWithdrawalDelayUpdate(); } /// @notice Lets the governance to begin an update of withdrawal timeout /// parameter value. The withdrawal timeout is the time the /// underwriter has - after the withdrawal delay passed - to /// complete the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalTimeoutUpdate after the required /// governance delay passes. It is up to the governance to /// decide what the withdrawal timeout value should be but it should /// be short enough so that the time of free-riding by being able to /// immediately escape from the claim is minimal and long enough so /// that honest underwriters have a possibility to finalize the /// withdrawal. It is all about the right proportions with /// a relation to withdrawal delay value. /// @param newWithdrawalTimeout The new value of the withdrawal timeout function beginWithdrawalTimeoutUpdate(uint256 newWithdrawalTimeout) external onlyOwner { assetPool.beginWithdrawalTimeoutUpdate(newWithdrawalTimeout); } /// @notice Lets the governance to finalize an update of withdrawal /// timeout parameter value. This call has to be preceded with /// a call to beginWithdrawalTimeoutUpdate and the governance delay /// has to pass. function finalizeWithdrawalTimeoutUpdate() external onlyOwner { assetPool.finalizeWithdrawalTimeoutUpdate(); } /// @notice Seizes funds from the coverage pool and puts them aside for the /// recipient to withdraw. /// @dev `portionToSeize` value was multiplied by `FLOATING_POINT_DIVISOR` /// for calculation precision purposes. Further calculations in this /// function will need to take this divisor into account. /// @param recipient Address that will receive the pool's seized funds /// @param portionToSeize Portion of the pool to seize in the range (0, 1] /// multiplied by `FLOATING_POINT_DIVISOR` function seizeFunds(address recipient, uint256 portionToSeize) external onlyApprovedRiskManager { require( portionToSeize > 0 && portionToSeize <= CoveragePoolConstants.FLOATING_POINT_DIVISOR, "Portion to seize is not within the range (0, 1]" ); assetPool.claim(recipient, amountToSeize(portionToSeize)); } /// @notice Grants asset pool shares by minting a given amount of the /// underwriter tokens for the recipient address. In result, the /// recipient obtains part of the pool ownership without depositing /// any collateral tokens. Shares are usually granted for notifiers /// reporting about various contract state changes. /// @dev Can be called only by an approved risk manager. /// @param recipient Address of the underwriter tokens recipient /// @param covAmount Amount of the underwriter tokens which should be minted function grantAssetPoolShares(address recipient, uint256 covAmount) external onlyApprovedRiskManager { assetPool.grantShares(recipient, covAmount); } /// @notice Returns the time remaining until the risk manager approval /// process can be finalized /// @param riskManager Risk manager in the process of approval /// @return Remaining time in seconds. function getRemainingRiskManagerApprovalTime(address riskManager) external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( riskManagerApprovalTimestamps[riskManager], assetPool.withdrawalGovernanceDelay() ); } /// @notice Calculates amount of tokens to be seized from the coverage pool. /// @param portionToSeize Portion of the pool to seize in the range (0, 1] /// multiplied by FLOATING_POINT_DIVISOR function amountToSeize(uint256 portionToSeize) public view returns (uint256) { return (collateralToken.balanceOf(address(assetPool)) * portionToSeize) / CoveragePoolConstants.FLOATING_POINT_DIVISOR; } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; library CoveragePoolConstants { // This divisor is for precision purposes only. We use this divisor around // auction related code to get the precise values without rounding it down // when dealing with floating numbers. uint256 public constant FLOATING_POINT_DIVISOR = 1e18; } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; library GovernanceUtils { /// @notice Gets the time remaining until the governable parameter update /// can be committed. /// @param changeTimestamp Timestamp indicating the beginning of the change. /// @param delay Governance delay. /// @return Remaining time in seconds. function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay) internal view returns (uint256) { require(changeTimestamp > 0, "Change not initiated"); /* solhint-disable-next-line not-rely-on-time */ uint256 elapsed = block.timestamp - changeTimestamp; if (elapsed >= delay) { return 0; } else { return delay - elapsed; } } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Rewards Pool /// @notice RewardsPool accepts a single reward token and releases it to the /// AssetPool over time in one week reward intervals. The owner of this /// contract is the reward distribution address funding it with reward /// tokens. contract RewardsPool is Ownable { using SafeERC20 for IERC20; uint256 public constant DURATION = 7 days; IERC20 public immutable rewardToken; address public immutable assetPool; // timestamp of the current reward interval end or the timestamp of the // last interval end in case a new reward interval has not been allocated uint256 public intervalFinish = 0; // rate per second with which reward tokens are unlocked uint256 public rewardRate = 0; // amount of rewards accumulated and not yet withdrawn from the previous // reward interval(s) uint256 public rewardAccumulated = 0; // the last time information in this contract was updated uint256 public lastUpdateTime = 0; event RewardToppedUp(uint256 amount); event RewardWithdrawn(uint256 amount); constructor( IERC20 _rewardToken, address _assetPool, address owner ) { rewardToken = _rewardToken; // slither-disable-next-line missing-zero-check assetPool = _assetPool; transferOwnership(owner); } /// @notice Transfers the provided reward amount into RewardsPool and /// creates a new, one-week reward interval starting from now. /// Reward tokens from the previous reward interval that unlocked /// over the time will be available for withdrawal immediately. /// Reward tokens from the previous interval that has not been yet /// unlocked, are added to the new interval being created. /// @dev This function can be called only by the owner given that it creates /// a new interval with one week length, starting from now. function topUpReward(uint256 reward) external onlyOwner { rewardAccumulated = earned(); /* solhint-disable not-rely-on-time */ if (block.timestamp >= intervalFinish) { // see https://github.com/crytic/slither/issues/844 // slither-disable-next-line divide-before-multiply rewardRate = reward / DURATION; } else { uint256 remaining = intervalFinish - block.timestamp; uint256 leftover = remaining * rewardRate; rewardRate = (reward + leftover) / DURATION; } intervalFinish = block.timestamp + DURATION; lastUpdateTime = block.timestamp; /* solhint-enable avoid-low-level-calls */ emit RewardToppedUp(reward); rewardToken.safeTransferFrom(msg.sender, address(this), reward); } /// @notice Withdraws all unlocked reward tokens to the AssetPool. function withdraw() external { uint256 amount = earned(); rewardAccumulated = 0; lastUpdateTime = lastTimeRewardApplicable(); emit RewardWithdrawn(amount); rewardToken.safeTransfer(assetPool, amount); } /// @notice Returns the amount of earned and not yet withdrawn reward /// tokens. function earned() public view returns (uint256) { return rewardAccumulated + ((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate); } /// @notice Returns the timestamp at which a reward was last time applicable. /// When reward interval is pending, returns current block's /// timestamp. If the last reward interval ended and no other reward /// interval had been allocated, returns the last reward interval's /// end timestamp. function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, intervalFinish); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IRiskManagerV1.sol"; import "./Auctioneer.sol"; import "./Auction.sol"; import "./CoveragePoolConstants.sol"; import "./GovernanceUtils.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title tBTC v1 Deposit contract interface /// @notice This is an interface with just a few function signatures of a main /// Deposit contract from tBTC. tBTC deposit contract functions declared in /// this interface are used by RiskManagerV1 contract to interact with tBTC /// v1 deposits. For more information about tBTC Deposit please see: /// https://github.com/keep-network/tbtc/blob/solidity/v1.1.0/solidity/contracts/deposit/Deposit.sol interface IDeposit { function withdrawFunds() external; function purchaseSignerBondsAtAuction() external; function currentState() external view returns (uint256); function lotSizeTbtc() external view returns (uint256); function withdrawableAmount() external view returns (uint256); function auctionValue() external view returns (uint256); } /// @title tBTC v1 deposit token (TDT) interface /// @notice This is an interface with just a few function signatures of a main /// contract from tBTC. For more information about tBTC Deposit please see: /// https://github.com/keep-network/tbtc/blob/solidity/v1.1.0/solidity/contracts/system/TBTCDepositToken.sol interface ITBTCDepositToken { function exists(uint256 _tokenId) external view returns (bool); } /// @title Signer bonds swap strategy /// @notice This interface is meant to abstract the underlying signer bonds /// swap strategy and make it interchangeable for the governance. /// Risk manager uses the strategy to swap ETH from tBTC deposit /// purchased signer bonds back into collateral token accepted by /// coverage pool. interface ISignerBondsSwapStrategy { /// @notice Notifies the strategy about signer bonds purchase. /// @param amount Amount of purchased signer bonds. function onSignerBondsPurchased(uint256 amount) external; } /// @title Risk Manager for tBTC v1 /// @notice Risk Manager is a smart contract with the exclusive right to claim /// coverage from the coverage pool. Demanding coverage is akin to /// filing a claim in traditional insurance and processing your own /// claim. The risk manager holds an incredibly privileged position, /// because the ability to claim coverage of an arbitrarily large /// position could bankrupt the coverage pool. /// tBTC v1 risk manager demands coverage by opening an auction for TBTC /// and liquidating portion of the coverage pool when tBTC v1 deposit is /// in liquidation and signer bonds on offer reached the specific /// threshold. In practice, it means no one is willing to purchase /// signer bonds for that deposit on tBTC side. contract RiskManagerV1 is IRiskManagerV1, Auctioneer, Ownable { using SafeERC20 for IERC20; using RiskManagerV1Rewards for RiskManagerV1Rewards.Storage; /// @notice Governance delay that needs to pass before any risk manager /// parameter change initiated by the governance takes effect. uint256 public constant GOVERNANCE_DELAY = 12 hours; // See https://github.com/keep-network/tbtc/blob/v1.1.0/solidity/contracts/deposit/DepositStates.sol uint256 public constant DEPOSIT_FRAUD_LIQUIDATION_IN_PROGRESS_STATE = 9; uint256 public constant DEPOSIT_LIQUIDATION_IN_PROGRESS_STATE = 10; uint256 public constant DEPOSIT_LIQUIDATED_STATE = 11; /// @notice Coverage pool auction will not be opened if the deposit's bond /// auction offers a bond percentage lower than this threshold. /// Risk manager should open a coverage pool auction for only those // tBTC deposits that nobody else is willing to purchase bonds /// from. The value can be updated by the governance in two steps. /// First step is to begin the update process with the new value /// and the second step is to finalize it after /// `GOVERNANCE_DELAY` has passed. uint256 public bondAuctionThreshold; // percentage uint256 public newBondAuctionThreshold; uint256 public bondAuctionThresholdChangeInitiated; /// @notice The length with which every new auction is opened. Auction length /// is the amount of time it takes for the auction to get to 100% /// of all collateral on offer, in seconds. This parameter value /// should be updated and kept up to date based on the coverage pool /// TVL and tBTC v1 minimum lot size allowed so that a new auction /// does not liquidate too much too early. Auction length is the /// same, no matter tBTC deposit lot size. /// The value can be updated by the governance in two steps. /// First step is to begin the update process with the new value /// and the second step is to finalize it after /// `GOVERNANCE_DELAY` has passed. uint256 public auctionLength; uint256 public newAuctionLength; uint256 public auctionLengthChangeInitiated; /// @notice The strategy used to swap ETH from tBTC deposit purchased signer /// bonds into an asset accepted by coverage pool as collateral. /// The value can be updated by the governance in two steps. /// First step is to begin the update process with the new value /// and the second step is to finalize it after /// `GOVERNANCE_DELAY` has passed. ISignerBondsSwapStrategy public signerBondsSwapStrategy; ISignerBondsSwapStrategy public newSignerBondsSwapStrategy; uint256 public signerBondsSwapStrategyInitiated; IERC20 public immutable tbtcToken; ITBTCDepositToken public immutable tbtcDepositToken; /// @notice TBTC surplus collected from early closed auctions. /// When tBTC deposit gets liquidated outside of coverage pools and /// an auction was opened earlier by the risk manager for that /// deposit, it might happen that the auction was partially filled /// and some TBTC from that auction has accumulated. In such a case, /// TBTC surplus left on the risk manager can be used to purchase /// signer bonds from another liquidating tBTC deposit in the future /// assuming enough surplus will accumulate up to that point. uint256 public tbtcSurplus; /// @notice Keeps track of notifier rewards for those calling /// `notifyLiquidation` and `notifyLiquidated`. RiskManagerV1Rewards.Storage public rewards; // deposit in liquidation => opened coverage pool auction mapping(address => address) public depositToAuction; // opened coverage pool auction => deposit in liquidation mapping(address => address) public auctionToDeposit; event NotifiedLiquidated(address indexed deposit, address notifier); event NotifiedLiquidation(address indexed deposit, address notifier); event BondAuctionThresholdUpdateStarted( uint256 bondAuctionThreshold, uint256 timestamp ); event BondAuctionThresholdUpdated(uint256 bondAuctionThreshold); event AuctionLengthUpdateStarted(uint256 auctionLength, uint256 timestamp); event AuctionLengthUpdated(uint256 auctionLength); event SignerBondsSwapStrategyUpdateStarted( address indexed signerBondsSwapStrategy, uint256 timestamp ); event SignerBondsSwapStrategyUpdated( address indexed signerBondsSwapStrategy ); event LiquidationNotifierRewardUpdateStarted( uint256 liquidationNotifierReward, uint256 timestamp ); event LiquidationNotifierRewardUpdated(uint256 liquidationNotifierReward); event LiquidatedNotifierRewardUpdateStarted( uint256 liquidatedNotifierReward, uint256 timestamp ); event LiquidatedNotifierRewardUpdated(uint256 liquidatedNotifierReward); /// @notice Reverts if called before the governance delay elapses. /// @param changeInitiatedTimestamp Timestamp indicating the beginning /// of the change. modifier onlyAfterGovernanceDelay(uint256 changeInitiatedTimestamp) { require(changeInitiatedTimestamp > 0, "Change not initiated"); require( /* solhint-disable-next-line not-rely-on-time */ block.timestamp - changeInitiatedTimestamp >= GOVERNANCE_DELAY, "Governance delay has not elapsed" ); _; } /// @notice Reverts if called by any account other than the current signer /// bonds swap strategy. modifier onlySignerBondsSwapStrategy() { require( msg.sender == address(signerBondsSwapStrategy), "Caller is not the signer bonds swap strategy" ); _; } constructor( IERC20 _tbtcToken, ITBTCDepositToken _tbtcDepositToken, CoveragePool _coveragePool, ISignerBondsSwapStrategy _signerBondsSwapStrategy, address _masterAuction, uint256 _auctionLength, uint256 _bondAuctionThreshold ) Auctioneer(_coveragePool, _masterAuction) { tbtcToken = _tbtcToken; tbtcDepositToken = _tbtcDepositToken; signerBondsSwapStrategy = _signerBondsSwapStrategy; auctionLength = _auctionLength; bondAuctionThreshold = _bondAuctionThreshold; } /// @notice Receives ETH from tBTC for purchasing and withdrawing deposit /// signer bonds. //slither-disable-next-line locked-ether receive() external payable {} /// @notice Notifies the risk manager about tBTC deposit in liquidation /// state for which signer bonds on offer passed the threshold /// expected by the risk manager. In practice, it means no one else /// is willing to purchase signer bonds from that deposit so the /// risk manager should open an auction to collect TBTC and purchase /// those bonds liquidating part of the coverage pool. If there is /// enough TBTC surplus from earlier auctions accumulated by the /// risk manager, bonds are purchased right away without opening an /// auction. Notifier calling this function receives a share in the /// coverage pool as a reward - underwriter tokens are transferred /// to the notifier's address. /// @param depositAddress liquidating tBTC deposit address function notifyLiquidation(address depositAddress) external override { require( tbtcDepositToken.exists(uint256(uint160(depositAddress))), "Address is not a deposit contract" ); IDeposit deposit = IDeposit(depositAddress); require( isDepositLiquidationInProgress(deposit), "Deposit is not in liquidation state" ); require( depositToAuction[depositAddress] == address(0), "Already notified on the deposit in liquidation" ); require( deposit.auctionValue() >= (address(deposit).balance * bondAuctionThreshold) / 100, "Deposit bond auction percentage is below the threshold level" ); uint256 lotSizeTbtc = deposit.lotSizeTbtc(); emit NotifiedLiquidation(depositAddress, msg.sender); // Reward the notifier by giving them some share of the pool. if (rewards.liquidationNotifierReward > 0) { // slither-disable-next-line reentrancy-benign coveragePool.grantAssetPoolShares( msg.sender, rewards.liquidationNotifierReward ); } // If the surplus can cover the deposit liquidation cost, liquidate // that deposit directly without the auction process. if (tbtcSurplus >= lotSizeTbtc) { tbtcSurplus -= lotSizeTbtc; liquidateDeposit(deposit); return; } // slither-disable-next-line reentrancy-no-eth address auctionAddress = createAuction( tbtcToken, lotSizeTbtc, auctionLength ); depositToAuction[depositAddress] = auctionAddress; auctionToDeposit[auctionAddress] = depositAddress; } /// @notice Notifies the risk manager about tBTC deposit liquidated outside /// the coverage pool for which the risk manager opened an auction /// earlier (as a result of `notifyLiquidation` call). Function /// closes the auction early and collects TBTC surplus from the /// auction in case the auction was partially taken before the /// deposit got liquidated. Notifier calling this function receives /// a share in the coverage pool as a reward - underwriter tokens /// are transferred to the notifier's address. /// @param depositAddress liquidated tBTC Deposit address function notifyLiquidated(address depositAddress) external override { require( depositToAuction[depositAddress] != address(0), "No auction for given deposit" ); IDeposit deposit = IDeposit(depositAddress); require( deposit.currentState() == DEPOSIT_LIQUIDATED_STATE, "Deposit is not in liquidated state" ); emit NotifiedLiquidated(depositAddress, msg.sender); Auction auction = Auction(depositToAuction[depositAddress]); delete depositToAuction[depositAddress]; delete auctionToDeposit[address(auction)]; uint256 amountTransferred = earlyCloseAuction(auction); // Add auction's transferred amount to the surplus pool. // slither-disable-next-line reentrancy-benign tbtcSurplus += amountTransferred; // Reward the notifier by giving them some share of the pool. if (rewards.liquidatedNotifierReward > 0) { coveragePool.grantAssetPoolShares( msg.sender, rewards.liquidatedNotifierReward ); } } /// @notice Begins the bond auction threshold update process. The value of /// the threshold must not be greater than 100. The threshold should /// be high enough so that the possibility of purchasing signer /// bonds outside of coverage pools after opening an auction is /// minimal. /// @dev Can be called only by the contract owner. /// @param _newBondAuctionThreshold New bond auction threshold in percent function beginBondAuctionThresholdUpdate(uint256 _newBondAuctionThreshold) external onlyOwner { require( _newBondAuctionThreshold <= 100, "Bond auction threshold must be lower or equal to 100" ); newBondAuctionThreshold = _newBondAuctionThreshold; /* solhint-disable-next-line not-rely-on-time */ bondAuctionThresholdChangeInitiated = block.timestamp; /* solhint-disable not-rely-on-time */ emit BondAuctionThresholdUpdateStarted( _newBondAuctionThreshold, block.timestamp ); } /// @notice Finalizes the bond auction threshold update process. /// @dev Can be called only by the contract owner, after the the /// governance delay elapses. function finalizeBondAuctionThresholdUpdate() external onlyOwner onlyAfterGovernanceDelay(bondAuctionThresholdChangeInitiated) { bondAuctionThreshold = newBondAuctionThreshold; emit BondAuctionThresholdUpdated(bondAuctionThreshold); bondAuctionThresholdChangeInitiated = 0; newBondAuctionThreshold = 0; } /// @notice Begins the auction length update process. The auction length /// should be adjusted very carefully. Total value locked of the /// coverage pool and minimum possible auction amount need to be /// taken into account. The goal is to find a "sweet spot" for /// auction length, not making it too short (which leads to big /// sums of coverage pool become available in a short time) and not /// making it too long (which leads to bidders waiting for too long /// until it will makes sense for them to bid on an auction). /// @dev Can be called only by the contract owner. /// @param _newAuctionLength New auction length in seconds function beginAuctionLengthUpdate(uint256 _newAuctionLength) external onlyOwner { newAuctionLength = _newAuctionLength; /* solhint-disable-next-line not-rely-on-time */ auctionLengthChangeInitiated = block.timestamp; /* solhint-disable-next-line not-rely-on-time */ emit AuctionLengthUpdateStarted(_newAuctionLength, block.timestamp); } /// @notice Finalizes the auction length update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeAuctionLengthUpdate() external onlyOwner onlyAfterGovernanceDelay(auctionLengthChangeInitiated) { auctionLength = newAuctionLength; emit AuctionLengthUpdated(newAuctionLength); newAuctionLength = 0; auctionLengthChangeInitiated = 0; } /// @notice Begins the liquidation notifier reward update process. /// Total value locked of the coverage pool and the cost of calling /// `notifyLiquidation` needs to be taken into account so that the /// call incentive is attractive enough and at the same time it does /// not offer to much value held the coverage pool. /// @dev Can be called only by the contract owner. /// @param _newLiquidationNotifierReward New liquidation notifier reward function beginLiquidationNotifierRewardUpdate( uint256 _newLiquidationNotifierReward ) external onlyOwner { /* solhint-disable-next-line not-rely-on-time */ emit LiquidationNotifierRewardUpdateStarted( _newLiquidationNotifierReward, block.timestamp ); rewards.beginLiquidationNotifierRewardUpdate( _newLiquidationNotifierReward ); } /// @notice Finalizes the liquidation notifier reward update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeLiquidationNotifierRewardUpdate() external onlyOwner onlyAfterGovernanceDelay( rewards.liquidationNotifierRewardChangeInitiated ) { emit LiquidationNotifierRewardUpdated( rewards.newLiquidationNotifierReward ); rewards.finalizeLiquidationNotifierRewardUpdate(); } /// @notice Begins the liquidated notifier reward update process. /// Total value locked of the coverage pool and the cost of calling /// `notifyLiquidated` needs to be taken into account so that the /// call incentive is attractive enough and at the same time it does /// not offer to much value held the coverage pool. /// @param _newLiquidatedNotifierReward New liquidated notifier reward function beginLiquidatedNotifierRewardUpdate( uint256 _newLiquidatedNotifierReward ) external onlyOwner { /* solhint-disable-next-line not-rely-on-time */ emit LiquidatedNotifierRewardUpdateStarted( _newLiquidatedNotifierReward, block.timestamp ); rewards.beginLiquidatedNotifierRewardUpdate( _newLiquidatedNotifierReward ); } /// @notice Finalizes the liquidated notifier reward update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses function finalizeLiquidatedNotifierRewardUpdate() external onlyOwner onlyAfterGovernanceDelay( rewards.liquidatedNotifierRewardChangeInitiated ) { emit LiquidatedNotifierRewardUpdated( rewards.newLiquidatedNotifierReward ); rewards.finalizeLiquidatedNotifierRewardUpdate(); } /// @notice Begins the signer bonds swap strategy update process. /// @dev Must be followed by a finalizeSignerBondsSwapStrategyUpdate after /// the governance delay elapses. /// @param _newSignerBondsSwapStrategy The new signer bonds swap strategy function beginSignerBondsSwapStrategyUpdate( ISignerBondsSwapStrategy _newSignerBondsSwapStrategy ) external onlyOwner { require( address(_newSignerBondsSwapStrategy) != address(0), "Invalid signer bonds swap strategy address" ); newSignerBondsSwapStrategy = _newSignerBondsSwapStrategy; /* solhint-disable-next-line not-rely-on-time */ signerBondsSwapStrategyInitiated = block.timestamp; emit SignerBondsSwapStrategyUpdateStarted( address(_newSignerBondsSwapStrategy), /* solhint-disable-next-line not-rely-on-time */ block.timestamp ); } /// @notice Finalizes the signer bonds swap strategy update. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeSignerBondsSwapStrategyUpdate() external onlyOwner onlyAfterGovernanceDelay(signerBondsSwapStrategyInitiated) { signerBondsSwapStrategy = newSignerBondsSwapStrategy; emit SignerBondsSwapStrategyUpdated( address(newSignerBondsSwapStrategy) ); delete newSignerBondsSwapStrategy; signerBondsSwapStrategyInitiated = 0; } /// @notice Withdraws the given amount of accumulated signer bonds. /// @dev Can be called only by the signer bonds swap strategy itself. /// This method should typically be used as part of the swap logic. /// Third-party calls may block funds on the strategy contract in case /// that strategy is not able to perform the swap. /// @param amount Amount of signer bonds being withdrawn function withdrawSignerBonds(uint256 amount) external override onlySignerBondsSwapStrategy { /* solhint-disable avoid-low-level-calls */ // slither-disable-next-line low-level-calls (bool success, ) = address(signerBondsSwapStrategy).call{value: amount}( "" ); require(success, "Failed to send Ether"); /* solhint-enable avoid-low-level-calls */ } /// @notice Get the time remaining until the bond auction threshold /// can be updated. /// @return Remaining time in seconds. function getRemainingBondAuctionThresholdUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( bondAuctionThresholdChangeInitiated, GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the auction length parameter /// can be updated. /// @return Remaining time in seconds. function getRemainingAuctionLengthUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( auctionLengthChangeInitiated, GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the liquidation notifier reward /// parameter can be updated. /// @return Remaining time in seconds. function getRemainingLiquidationNotifierRewardUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( rewards.liquidationNotifierRewardChangeInitiated, GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the liquidated notifier reward /// amount parameter can be updated. /// @return Remaining time in seconds. function getRemainingLiquidatedNotifierRewardUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( rewards.liquidatedNotifierRewardChangeInitiated, GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the signer bonds swap strategy /// can be changed. /// @return Remaining time in seconds. function getRemainingSignerBondsSwapStrategyChangeTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( signerBondsSwapStrategyInitiated, GOVERNANCE_DELAY ); } /// @return True if there are open auctions managed by the risk manager. /// Returns false otherwise. function hasOpenAuctions() external view override returns (bool) { return openAuctionsCount > 0; } /// @return Current value of the liquidation notifier reward. function liquidationNotifierReward() external view returns (uint256) { return rewards.liquidationNotifierReward; } /// @return Current value of the liquidated notifier reward. function liquidatedNotifierReward() external view returns (uint256) { return rewards.liquidatedNotifierReward; } /// @notice Cleans up auction and deposit data and executes deposit liquidation. /// @dev This function is invoked when Auctioneer determines that an auction /// is eligible to be closed. It cannot be called on-demand outside /// the Auctioneer contract. By the time this function is called, all /// the TBTC tokens for the coverage pool auction should be transferred /// to this contract in order to buy signer bonds. /// @param auction Coverage pool auction function onAuctionFullyFilled(Auction auction) internal override { IDeposit deposit = IDeposit(auctionToDeposit[address(auction)]); // Make sure the deposit was not liquidated outside of Coverage Pool require( isDepositLiquidationInProgress(deposit), "Deposit liquidation is not in progress" ); delete depositToAuction[address(deposit)]; delete auctionToDeposit[address(auction)]; liquidateDeposit(deposit); } /// @notice Purchases ETH from signer bonds and swaps obtained funds /// using the underlying signer bonds swap strategy. /// @dev By the time this function is called, TBTC token balance for this /// contract should be enough to buy signer bonds. /// @param deposit TBTC deposit which should be liquidated. function liquidateDeposit(IDeposit deposit) internal { uint256 approvedAmount = deposit.lotSizeTbtc(); tbtcToken.safeApprove(address(deposit), approvedAmount); // Purchase signers bonds ETH with TBTC acquired from the auction or // taken from the surplus pool. deposit.purchaseSignerBondsAtAuction(); uint256 withdrawableAmount = deposit.withdrawableAmount(); deposit.withdrawFunds(); signerBondsSwapStrategy.onSignerBondsPurchased(withdrawableAmount); } /// @notice Reverts if the deposit for which the auction was created is no /// longer in the liquidation state. This could happen if signer /// bonds were purchased from tBTC deposit directly, outside of /// coverage pool auction. /// @dev This function is invoked when the auctioneer is informed about the /// results of an auction and the auction was partially filled. /// @param auction Address of an auction whose deposit needs to be checked. function onAuctionPartiallyFilled(Auction auction) internal view override { IDeposit deposit = IDeposit(auctionToDeposit[address(auction)]); // Make sure the deposit was not liquidated outside of Coverage Pool require( isDepositLiquidationInProgress(deposit), "Deposit liquidation is not in progress" ); } function isDepositLiquidationInProgress(IDeposit deposit) internal view returns (bool) { uint256 state = deposit.currentState(); return (state == DEPOSIT_LIQUIDATION_IN_PROGRESS_STATE || state == DEPOSIT_FRAUD_LIQUIDATION_IN_PROGRESS_STATE); } } /// @title RiskManagerV1Rewards /// @notice Contains logic responsible for calculating notifier rewards for /// both deposit liquidation start and deposit liquidated events. /// All parameters can be updated using a two-phase process. /// @dev The client contract should take care of authorizations or governance /// delays according to their needs. /* solhint-disable-next-line ordering */ library RiskManagerV1Rewards { struct Storage { // Amount of COV tokens which should be given as reward for the // notifier reporting about the start of deposit liquidation process. uint256 liquidationNotifierReward; uint256 newLiquidationNotifierReward; uint256 liquidationNotifierRewardChangeInitiated; // Amount of COV tokens which should be given as reward for the // notifier reporting about a deposit being liquidated outside of the // coverage pool. uint256 liquidatedNotifierReward; uint256 newLiquidatedNotifierReward; uint256 liquidatedNotifierRewardChangeInitiated; } /// @notice Begins the liquidation notifier reward update process. /// @param _newLiquidationNotifierReward New liquidation notifier reward. function beginLiquidationNotifierRewardUpdate( Storage storage self, uint256 _newLiquidationNotifierReward ) internal { /* solhint-disable not-rely-on-time */ self.newLiquidationNotifierReward = _newLiquidationNotifierReward; self.liquidationNotifierRewardChangeInitiated = block.timestamp; /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the liquidation notifier reward update process. function finalizeLiquidationNotifierRewardUpdate(Storage storage self) internal { self.liquidationNotifierReward = self.newLiquidationNotifierReward; self.newLiquidationNotifierReward = 0; self.liquidationNotifierRewardChangeInitiated = 0; } /// @notice Begins the liquidated notifier reward update process. /// @param _newLiquidatedNotifierReward New liquidated notifier reward function beginLiquidatedNotifierRewardUpdate( Storage storage self, uint256 _newLiquidatedNotifierReward ) internal { /* solhint-disable not-rely-on-time */ self.newLiquidatedNotifierReward = _newLiquidatedNotifierReward; self.liquidatedNotifierRewardChangeInitiated = block.timestamp; /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the liquidated notifier reward update process. function finalizeLiquidatedNotifierRewardUpdate(Storage storage self) internal { self.liquidatedNotifierReward = self.newLiquidatedNotifierReward; self.newLiquidatedNotifierReward = 0; self.liquidatedNotifierRewardChangeInitiated = 0; } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IRiskManagerV1.sol"; import "./RiskManagerV1.sol"; import "./CoveragePool.sol"; import "./CoveragePoolConstants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @notice Interface for the Uniswap v2 router. /// @dev This is an interface with just a few function signatures of the /// router contract. For more info and function description please see: /// https://uniswap.org/docs/v2/smart-contracts/router02 interface IUniswapV2Router { function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function factory() external pure returns (address); /* solhint-disable-next-line func-name-mixedcase */ function WETH() external pure returns (address); } /// @notice Interface for the Uniswap v2 pair. /// @dev This is an interface with just a few function signatures of the /// pair contract. For more info and function description please see: /// https://uniswap.org/docs/v2/smart-contracts/pair interface IUniswapV2Pair { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } /// @title SignerBondsUniswapV2 /// @notice ETH purchased by the risk manager from tBTC signer bonds needs to be /// swapped and deposited back to the coverage pool as collateral. /// SignerBondsUniswapV2 is a swap strategy implementation which /// can withdraw the given bonds amount from the risk manager, swap them /// on Uniswap v2 exchange and deposit as coverage pool collateral. /// The governance can set crucial swap parameters: max allowed /// percentage impact, slippage tolerance and swap deadline, to force /// reasonable swap outcomes. It is up to the governance to decide what /// these values should be. contract SignerBondsUniswapV2 is ISignerBondsSwapStrategy, Ownable { // One basis point is equivalent to 1/100th of a percent. uint256 public constant BASIS_POINTS_DIVISOR = 10000; IUniswapV2Router public immutable uniswapRouter; IUniswapV2Pair public immutable uniswapPair; address public immutable assetPool; address public immutable collateralToken; mapping(address => bool) public approvedSwappers; // Determines the maximum allowed price impact for the swap transaction. // If transaction's price impact is higher, transaction will be reverted. // Default value is 100 basis points (1%). uint256 public maxAllowedPriceImpact = 100; // Determines the slippage tolerance for the swap transaction. // If transaction's slippage is higher, transaction will be reverted. // Default value is 50 basis points (0.5%). uint256 public slippageTolerance = 50; // Determines the deadline in which the swap transaction has to be mined. // If that deadline is exceeded, transaction will be reverted. uint256 public swapDeadline = 20 minutes; // Determines if the swap should revert when open auctions exists. If true, // swaps cannot be performed if there is at least one open auction. // If false, open auctions are not taken into account. bool public revertIfAuctionOpen = true; event SignerBondsSwapperApproved(address swapper); event SignerBondsSwapperUnapproved(address swapper); event UniswapV2SwapExecuted(uint256[] amounts); /// @notice Reverts if called by a signer bonds swapper that is not approved modifier onlyApprovedSwapper() { require( approvedSwappers[msg.sender], "Signer bonds swapper not approved" ); _; } constructor(IUniswapV2Router _uniswapRouter, CoveragePool _coveragePool) { uniswapRouter = _uniswapRouter; assetPool = address(_coveragePool.assetPool()); address _collateralToken = address(_coveragePool.collateralToken()); collateralToken = _collateralToken; uniswapPair = IUniswapV2Pair( computePairAddress( _uniswapRouter.factory(), _uniswapRouter.WETH(), _collateralToken ) ); } /// @notice Receive ETH upon withdrawal of risk manager's signer bonds. /// @dev Do not send arbitrary funds. They will be locked forever. receive() external payable {} /// @notice Notifies the strategy about signer bonds purchase. /// @param amount Amount of purchased signer bonds. function onSignerBondsPurchased(uint256 amount) external override {} /// @notice Sets the maximum price impact allowed for a swap transaction. /// @param _maxAllowedPriceImpact Maximum allowed price impact specified /// in basis points. Value of this parameter must be between /// 0 and 10000 (inclusive). It should be chosen carefully as /// high limit level will accept transactions with high volumes. /// Those transactions may result in poor execution prices. Very low /// limit will force low swap volumes. Limit equal to 0 will /// effectively make swaps impossible. function setMaxAllowedPriceImpact(uint256 _maxAllowedPriceImpact) external onlyOwner { require( _maxAllowedPriceImpact <= BASIS_POINTS_DIVISOR, "Maximum value is 10000 basis points" ); maxAllowedPriceImpact = _maxAllowedPriceImpact; } /// @notice Sets the slippage tolerance for a swap transaction. /// @param _slippageTolerance Slippage tolerance in basis points. Value of /// this parameter must be between 0 and 10000 (inclusive). It /// should be chosen carefully as transactions with high slippage /// tolerance result in poor execution prices. On the other hand, /// very low slippage tolerance may cause transactions to be /// reverted frequently. Slippage tolerance equal to 0 is possible /// and disallows any slippage to happen on the swap at the cost /// of higher revert risk. function setSlippageTolerance(uint256 _slippageTolerance) external onlyOwner { require( _slippageTolerance <= BASIS_POINTS_DIVISOR, "Maximum value is 10000 basis points" ); slippageTolerance = _slippageTolerance; } /// @notice Sets the deadline for a swap transaction. /// @param _swapDeadline Swap deadline in seconds. Value of this parameter /// should be equal or greater than 0. It should be chosen carefully /// as transactions with long deadlines may result in poor execution /// prices. On the other hand, very short deadlines may cause /// transactions to be reverted frequently, especially in a /// gas-expensive environment. Deadline equal to 0 will effectively // make swaps impossible. function setSwapDeadline(uint256 _swapDeadline) external onlyOwner { swapDeadline = _swapDeadline; } /// @notice Sets whether a swap should revert if at least one /// open auction exists. /// @param _revertIfAuctionOpen If true, revert the swap if there is at /// least one open auction. If false, open auctions won't be taken /// into account. function setRevertIfAuctionOpen(bool _revertIfAuctionOpen) external onlyOwner { revertIfAuctionOpen = _revertIfAuctionOpen; } /// @notice Swaps signer bonds on Uniswap v2 exchange. /// @dev Swaps the given ETH amount for the collateral token using the /// Uniswap exchange. The maximum ETH amount is capped by the /// contract balance. Some governance parameters are applied on the /// transaction. The swap's price impact must fit within the /// maximum allowed price impact and the transaction is constrained /// with the slippage tolerance and deadline. Acquired collateral /// tokens are sent to the asset pool address set during /// contract construction. /// @param riskManager Address of the risk manager which holds the bonds. /// @param amount Amount to swap. function swapSignerBondsOnUniswapV2( IRiskManagerV1 riskManager, uint256 amount ) external onlyApprovedSwapper { require(amount > 0, "Amount must be greater than 0"); require( amount <= address(riskManager).balance, "Amount exceeds risk manager balance" ); if (revertIfAuctionOpen) { require(!riskManager.hasOpenAuctions(), "There are open auctions"); } riskManager.withdrawSignerBonds(amount); // Setup the swap path. WETH must be the first component. address[] memory path = new address[](2); path[0] = uniswapRouter.WETH(); path[1] = collateralToken; // Calculate the maximum output token amount basing on pair reserves. // This value will be used as the minimum amount of output tokens that // must be received for the transaction not to revert. // This value includes liquidity fee equal to 0.3%. uint256 amountOutMin = uniswapRouter.getAmountsOut(amount, path)[1]; require( isAllowedPriceImpact(amountOutMin), "Price impact exceeds allowed limit" ); // Include slippage tolerance into the minimum amount of output tokens. amountOutMin = (amountOutMin * (BASIS_POINTS_DIVISOR - slippageTolerance)) / BASIS_POINTS_DIVISOR; // slither-disable-next-line arbitrary-send,reentrancy-events uint256[] memory amounts = uniswapRouter.swapExactETHForTokens{ value: amount }( amountOutMin, path, assetPool, /* solhint-disable-next-line not-rely-on-time */ block.timestamp + swapDeadline ); emit UniswapV2SwapExecuted(amounts); } /// @notice Approves the signer bonds swapper. The change takes effect /// immediately. /// @dev Can be called only by the contract owner. /// @param swapper Swapper that will be approved function approveSwapper(address swapper) external onlyOwner { require( !approvedSwappers[swapper], "Signer bonds swapper has been already approved" ); emit SignerBondsSwapperApproved(swapper); approvedSwappers[swapper] = true; } /// @notice Unapproves the signer bonds swapper. The change takes effect /// immediately. /// @dev Can be called only by the contract owner. /// @param swapper Swapper that will be unapproved function unapproveSwapper(address swapper) external onlyOwner { require( approvedSwappers[swapper], "Signer bonds swapper is not approved" ); emit SignerBondsSwapperUnapproved(swapper); delete approvedSwappers[swapper]; } /// @notice Checks the price impact of buying a given amount of tokens /// against the maximum allowed price impact limit. /// @param amount Amount of tokens. /// @return True if the price impact is allowed, false otherwise. function isAllowedPriceImpact(uint256 amount) public view returns (bool) { // Get reserve of the collateral token. address WETH = uniswapRouter.WETH(); address token0 = WETH < collateralToken ? WETH : collateralToken; (uint256 reserve0, uint256 reserve1, ) = uniswapPair.getReserves(); uint256 collateralTokenReserve = WETH == token0 ? reserve1 : reserve0; // Same as: priceImpact <= priceImpactLimit return amount * BASIS_POINTS_DIVISOR <= maxAllowedPriceImpact * collateralTokenReserve; } /// @notice Compute Uniswap v2 pair address. /// @param factory Address of the Uniswap v2 factory. /// @param tokenA Address of token A. /// @param tokenB Address of token B. /// @return Address of token pair. function computePairAddress( address factory, address tokenA, address tokenB ) internal pure returns (address) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); return address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" ) ) ) ) ); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "@thesis/solidity-contracts/contracts/token/ERC20WithPermit.sol"; /// @title UnderwriterToken /// @notice Underwriter tokens represent an ownership share in the underlying /// collateral of the asset-specific pool. Underwriter tokens are minted /// when a user deposits ERC20 tokens into asset-specific pool and they /// are burned when a user exits the position. Underwriter tokens /// natively support meta transactions. Users can authorize a transfer /// of their underwriter tokens with a signature conforming EIP712 /// standard instead of an on-chain transaction from their address. /// Anyone can submit this signature on the user's behalf by calling the /// permit function, as specified in EIP2612 standard, paying gas fees, /// and possibly performing other actions in the same transaction. contract UnderwriterToken is ERC20WithPermit { constructor(string memory _name, string memory _symbol) ERC20WithPermit(_name, _symbol) {} } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Asset Pool interface /// @notice Asset Pool accepts a single ERC20 token as collateral, and returns /// an underwriter token. For example, an asset pool might accept deposits /// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens /// represent an ownership share in the underlying collateral of the /// Asset Pool. interface IAssetPool { /// @notice Accepts the given amount of collateral token as a deposit and /// mints underwriter tokens representing pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @return The amount of minted underwriter tokens function deposit(uint256 amount) external returns (uint256); /// @notice Accepts the given amount of collateral token as a deposit and /// mints at least a minAmountToMint underwriter tokens representing /// pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @return The amount of minted underwriter tokens function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint) external returns (uint256); /// @notice Initiates the withdrawal of collateral and rewards from the pool. /// @dev Before calling this function, underwriter token needs to have the /// required amount accepted to transfer to the asset pool. function initiateWithdrawal(uint256 covAmount) external; /// @notice Completes the previously initiated withdrawal for the /// underwriter. /// @return The amount of collateral withdrawn function completeWithdrawal(address underwriter) external returns (uint256); } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Asset Pool upgrade interface /// @notice Interface that has to be implemented by an Asset Pool accepting /// upgrades from another asset pool. interface IAssetPoolUpgrade { /// @notice Accepts the given underwriter with collateral tokens amount as a /// deposit. In exchange new underwriter tokens will be calculated, /// minted and then transferred back to the underwriter. function depositFor(address underwriter, uint256 amount) external; } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Auction interface /// @notice Auction runs a linear falling-price auction against a diverse /// basket of assets held in a collateral pool. Auctions are taken using /// a single asset. Over time, a larger and larger portion of the assets /// are on offer, eventually hitting 100% of the backing collateral interface IAuction { /// @notice Takes an offer from an auction buyer. There are two possible /// ways to take an offer from a buyer. The first one is to buy /// entire auction with the amount desired for this auction. /// The other way is to buy a portion of an auction. In this case an /// auction depleting rate is increased. /// @dev The implementation is not guaranteed to be protecting against /// frontrunning. See `AuctionBidder` for an example protection. function takeOffer(uint256 amount) external; /// @notice How much of the collateral pool can currently be purchased at /// auction, across all assets. /// @return The ratio of the collateral pool currently on offer and divisor /// for precision purposes. function onOffer() external view returns (uint256, uint256); } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Interface for tBTC v1 Risk Manager /// @notice Risk Manager is a smart contract with the exclusive right to claim /// coverage from the coverage pool. Demanding coverage is akin to /// filing a claim in traditional insurance and processing your own /// claim. The risk manager holds an incredibly privileged position, /// because the ability to claim coverage of an arbitrarily large /// position could bankrupt the coverage pool. /// tBTC v1 risk manager demands coverage by opening an auction for TBTC /// and liquidating portion of the coverage pool when tBTC v1 deposit is /// in liquidation and signer bonds on offer reached the specific /// threshold. In practice, it means no one is willing to purchase /// signer bonds for that deposit on tBTC side. interface IRiskManagerV1 { /// @notice Notifies the risk manager about tBTC deposit in liquidation /// state for which signer bonds on offer passed the threshold /// expected by the risk manager. In practice, it means no one else /// is willing to purchase signer bonds from that deposit so the /// risk manager should open an auction to collect TBTC and purchase /// those bonds liquidating part of the coverage pool. If there is /// enough TBTC surplus from earlier auctions accumulated by the /// risk manager, bonds are purchased right away without opening an /// auction. Notifier calling this function receives a share in the /// coverage pool as a reward - underwriter tokens are transferred /// to the notifier's address. /// @param depositAddress liquidating tBTC deposit address function notifyLiquidation(address depositAddress) external; /// @notice Notifies the risk manager about tBTC deposit liquidated outside /// the coverage pool for which the risk manager opened an auction /// earlier (as a result of `notifyLiquidation` call). Function /// closes the auction early and collects TBTC surplus from the /// auction in case the auction was partially taken before the /// deposit got liquidated. Notifier calling this function receives /// a share in the coverage pool as a reward - underwriter tokens /// are transferred to the notifier's address. /// @param depositAddress liquidated tBTC Deposit address function notifyLiquidated(address depositAddress) external; /// @notice Withdraws the given amount of accumulated signer bonds. /// @dev Usually used by `ISignerBondsSwapStrategy` implementations. /// @param amount Amount of signer bonds being withdrawn. function withdrawSignerBonds(uint256 amount) external; /// @notice Returns true if there are open auctions managed by the risk /// manager. Returns false otherwise. /// @dev Usually used by `ISignerBondsSwapStrategy` implementations. function hasOpenAuctions() external view returns (bool); }
Begins the liquidation notifier reward update process. _newLiquidationNotifierReward New liquidation notifier reward.
function beginLiquidationNotifierRewardUpdate( Storage storage self, uint256 _newLiquidationNotifierReward ) internal { self.newLiquidationNotifierReward = _newLiquidationNotifierReward; self.liquidationNotifierRewardChangeInitiated = block.timestamp;
11,901,982
./full_match/1/0x94eEf006D2691BE320632eA05C0789Aae1b8b82B/sources/contracts/NFT20Pair.sol
withdraw nft and burn tokens
function withdraw( uint256[] calldata _tokenIds, uint256[] calldata amounts, address recipient ) external { if (nftType == 1155) { if (_tokenIds.length == 1) { _burn(msg.sender, nftValue.mul(amounts[0])); _withdraw1155( address(this), recipient, _tokenIds[0], amounts[0] ); _batchWithdraw1155( address(this), recipient, _tokenIds, amounts ); } _burn(msg.sender, nftValue.mul(_tokenIds.length)); for (uint256 i = 0; i < _tokenIds.length; i++) { _withdraw721(address(this), recipient, _tokenIds[i]); } } emit Withdraw(_tokenIds, amounts); }
3,039,803
./full_match/42220/0xf73F4Ca21A86F41330073C4C7D9b5367eCC208C0/sources/contracts/learnAndEarn/LearnAndEarnImplementation.sol
Updates a level _levelId the id of the level _token the token used for reward/
function updateLevel(uint256 _levelId, IERC20 _token) external override onlyOwnerOrImpactMarketCouncil { require( levels[_levelId].state == LevelState.Valid, "LearnAndLearn::updateLevel: Invalid level id" ); require(levels[_levelId].balance == 0, "LearnAndLearn::updateLevel: This level has funds"); levels[_levelId].token = _token; emit LevelUpdated(_levelId, address(_token)); }
16,353,682
./full_match/1/0xd636b1967aA1ee74785f1bf8bBc8227B621d3B62/sources/contracts/Juti.sol
Mint state for Public Mint, WhiteList Mint & FreeMint
function setPublicMintState(bool _state) external onlyOwner { isPublicMintState = _state; }
2,985,944
pragma solidity >=0.5.0; import "./openzeppelin/Ownable.sol"; import "./openzeppelin/SupportsInterfaceWithLookup.sol"; import "./openzeppelin/ERC721Basic.sol"; import "./openzeppelin/ERC721.sol"; import "./openzeppelin/ERC721Receiver.sol"; import "./openzeppelin/SafeMath.sol"; import "./openzeppelin/AddressUtils.sol"; import "./snarklibs/SnarkBaseLib.sol"; import "./snarklibs/SnarkBaseExtraLib.sol"; import "./snarklibs/SnarkCommonLib.sol"; import "./snarklibs/SnarkLoanLib.sol"; contract SnarkERC721 is Ownable, SupportsInterfaceWithLookup, ERC721 { using SafeMath for uint256; using AddressUtils for address; using SnarkBaseLib for address; using SnarkBaseExtraLib for address; using SnarkCommonLib for address; using SnarkLoanLib for address; address payable private _storage; bytes4 private constant ERC721_RECEIVED = 0x150b7a02; /// @dev Checks msg.sender can transfer a token - limited to owner or those approved by owner, an operator /// @param _tokenId uint256 ID of the token to validate modifier canTransfer(uint256 _tokenId) { require( _isApprovedOrOwner(msg.sender, _tokenId), "You have to be either token owner or be approved by owner" ); _; } modifier correctToken(uint256 _tokenId) { require( _tokenId > 0 && _tokenId <= SnarkBaseLib.getTotalNumberOfTokens(_storage), "Token is not correct" ); _; } constructor(address payable storageAddress) public { // get an address of a storage _storage = storageAddress; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(INTERFACEID_ERC721); _registerInterface(INTERFACEID_ERC721EXISTS); _registerInterface(INTERFACEID_ERC721ENUMERABLE); _registerInterface(INTERFACEID_ERC721METADATA); } /// @notice Will receive any eth sent to the contract function() external payable {} // solhint-disable-line /// @dev Function to destroy the contract on the blockchain function kill() external onlyOwner { selfdestruct(msg.sender); } /********************/ /** ERC721Metadata **/ /********************/ /// @dev Gets the token name /// @return string representing the token name function name() public view returns (string memory) { return SnarkBaseLib.getTokenName(_storage); } /// @dev Gets the token symbol /// @return string representing the token symbol function symbol() public view returns (string memory) { return SnarkBaseLib.getTokenSymbol(_storage); } /// @dev Returns an URI for a given token ID /// Throws if the token ID does not exist. May return an empty string. /// @param _tokenId uint256 ID of the token to query function tokenURI(uint256 _tokenId) public view correctToken(_tokenId) returns (string memory) { return SnarkBaseLib.getDecorationUrl(_storage, _tokenId); } /**********************/ /** ERC721Enumerable **/ /**********************/ function totalSupply() public view returns (uint256) { return SnarkBaseLib.getTotalNumberOfTokens(_storage); } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) { require(_index < balanceOf(_owner)); uint256 tokenId; uint256 loanId = SnarkLoanLib.getLoanId(_storage); bool isActive = SnarkLoanLib.isLoanActive(_storage, loanId); address loanOwner = SnarkLoanLib.getOwnerOfLoan(_storage, loanId); if (isActive && _owner == loanOwner) { uint256 countOfNotApprovedTokens = SnarkLoanLib.getTotalNumberOfTokensInNotApprovedTokensForLoan(_storage, _owner); if (_index < countOfNotApprovedTokens) { tokenId = SnarkLoanLib.getTokenFromNotApprovedTokensForLoanByIndex(_storage, _owner, _index); } else { uint256 index = _index - countOfNotApprovedTokens; tokenId = SnarkLoanLib.getTokenFromApprovedTokensForLoanByIndex(_storage, index); } } else { tokenId = SnarkBaseLib.getTokenIdOfOwner(_storage, _owner, _index); } return tokenId; } // Considers case when loan is active function tokenOfRealOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId, address _realOwner) { _tokenId = tokenOfOwnerByIndex(_owner, _index); _realOwner = ownerOf(_tokenId); } function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return _index.add(1); } /*****************/ /** ERC721Basic **/ /*****************/ /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); uint256 balance = 0; uint256 loanId = SnarkLoanLib.getLoanId(_storage); if (SnarkLoanLib.isLoanActive(_storage, loanId) && _owner == SnarkLoanLib.getOwnerOfLoan(_storage, loanId) ) { balance = SnarkLoanLib.getTotalNumberOfTokensInApprovedTokensForLoan(_storage); balance += SnarkLoanLib.getTotalNumberOfTokensInNotApprovedTokensForLoan(_storage, _owner); } else { balance = SnarkBaseLib.getOwnedTokensCount(_storage, _owner); } return balance; } /// @notice Find the owner of an NFT /// @param _tokenId The identifier for an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) public view correctToken(_tokenId) returns (address) { address tokenOwner = SnarkBaseLib.getOwnerOfToken(_storage, _tokenId); require(tokenOwner != address(0)); return tokenOwner; } /// @dev Returns whether the specified token exists /// @param _tokenId uint256 ID of the token to query the existance of /// @return whether the token exists function exists(uint256 _tokenId) public view returns (bool _exists) { return (SnarkBaseLib.getOwnerOfToken(_storage, _tokenId) != address(0)); } /// @notice Set or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @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 correctToken(_tokenId) { address tokenOwner = ownerOf(_tokenId); require(tokenOwner != _to); require(msg.sender == tokenOwner || isApprovedForAll(tokenOwner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { SnarkBaseLib.setApprovalsToToken(_storage, tokenOwner, _tokenId, _to); emit Approval(msg.sender, _to, _tokenId); } } /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) public view correctToken(_tokenId) returns (address _operator) { address tokenOwner = ownerOf(_tokenId); return SnarkBaseLib.getApprovalsToToken(_storage, tokenOwner, _tokenId); } /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets. /// @dev Emits the ApprovalForAll event /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) public { require(_operator != msg.sender); SnarkBaseLib.setApprovalsToOperator(_storage, msg.sender, _operator, _approved); emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return SnarkBaseLib.getApprovalsToOperator(_storage, _owner, _operator); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) correctToken(_tokenId) payable { require(_from != address(0), "Sender's address can't be equal zero"); require(_to != address(0), "Receiver's address can't be equal zero"); require(_from != _to, "Sender's address can't be equal receiver's address"); _clearApproval(_from, _tokenId); SnarkLoanLib.toShiftPointer(_storage); if (SnarkLoanLib.isTokenInNotApprovedListForLoan(_storage, _from, _tokenId)) { SnarkLoanLib.deleteTokenFromNotApprovedListForLoan(_storage, _from, _tokenId); SnarkLoanLib.addTokenToNotApprovedListForLoan(_storage, _to, _tokenId); } if (msg.value > 0) { _storage.transfer(msg.value); SnarkCommonLib.buy(_storage, _tokenId, msg.value, _from, _to); } else { SnarkCommonLib.transferToken(_storage, _tokenId, _from, _to); } emit Transfer(_from, _to, _tokenId); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "" /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) payable { safeTransferFrom(_from, _to, _tokenId, ""); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) public canTransfer(_tokenId) payable { transferFrom(_from, _to, _tokenId); require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } function echoTransfer(address _from, address _to, uint256 _tokenId) public { emit Transfer(_from, _to, _tokenId); } /// @dev Internal function to clear current approval of a given token ID /// @dev Reverts if the given address is not indeed the owner of the token /// @param _owner owner of the token /// @param _tokenId uint256 ID of the token to be transferred function _clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (SnarkBaseLib.getApprovalsToToken(_storage, _owner, _tokenId) != address(0)) { SnarkBaseLib.setApprovalsToToken(_storage, _owner, _tokenId, address(0)); emit Approval(_owner, address(0), _tokenId); } } /// @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, /// the owner or an operator of the owner of the token function _isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address tokenOwner = ownerOf(_tokenId); return ( _spender == tokenOwner || getApproved(_tokenId) == _spender || isApprovedForAll(tokenOwner, _spender) ); } /// @dev Internal function to invoke `onERC721Received` on a target address /// @dev 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 _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } }
/ ERC721Enumerable //
function totalSupply() public view returns (uint256) { return SnarkBaseLib.getTotalNumberOfTokens(_storage); }
6,366,998
./partial_match/1/0xa28C3111C57f5EA3cb09e06C7C7406eba49068b4/sources/BzxLiquidateV2.sol
IBZx.LoanReturnData memory loan = BZX.getLoan(loanId); require(maxLiquidatable != 0, "healty loan"); IToken iToken = IToken(BZX.underlyingToLoanPool(loanToken));
function liquidateInternal( bytes32 loanId, address loanToken, address collateralToken, uint256 maxLiquidatable, address flashLoanToken, bool allowLoss ) internal returns (address, uint256) { bytes memory b = IToken(flashLoanToken).flashBorrow( maxLiquidatable, address(this), address(this), "", abi.encodeWithSignature( "executeOperation(bytes32,address,address,uint256,address,bool)", loanId, loanToken, collateralToken, maxLiquidatable, flashLoanToken, allowLoss ) ); (, , , uint256 profitAmount) = abi.decode( b, (uint256, uint256, address, uint256) ); return (loanToken, profitAmount); }
15,484,762
pragma solidity 0.4.24; import "./libraries/openzeppelin/migrations/Initializable.sol"; import "./libraries/tokenfoundry/StateMachine.sol"; import "./libraries/openzeppelin/ECRecovery.sol"; import "./libraries/Bytes.sol"; /// @title Battleship game over state channels. /// @author Ricardo Rius - <[email protected]> contract Battleship is StateMachine,Initializable { using ECRecovery for bytes32; // GAME STATES bytes32 constant STATE1 = "Create"; bytes32 constant STATE2 = "Set"; bytes32 constant STATE3 = "Play"; bytes32 constant STATE4 = "GameOver"; bytes32[] states = [STATE1, STATE2, STATE3, STATE4]; // FUNCTION SIGNATURES bytes4 private constant REGISTRY_PLAYERS_FSIG = bytes4(keccak256("setPlayer(address,uint256,uint256)")); bytes4 private constant REGISTRY_GAME_OWNER_FSIG = bytes4(keccak256("setGameOwner()")); bytes4 private constant REGISTRY_WINNER_FSIG = bytes4(keccak256("setWinner(address)")); // STATE VARIABLES address public owner; address public player1; address public player2; address public playerTurn; address public winner; uint public nonce; uint public betAmt; uint public timeout; mapping(address => address) public playerSigner; mapping(address => bytes32) internal hiddenShips; mapping(address => uint[]) internal playerShips; mapping(address => uint[]) internal playerMoves; mapping(address => uint[]) internal hitsToPlayer; mapping(address => uint[]) internal notHitsToPlayer; mapping(address => bytes4) internal secret; address internal ethrReg;// Ethr DID Registry address internal gameReg;// Game Registry string internal topic; // Whisper Channel Topic uint internal timeoutInterval; bool internal fairGame; /// @dev Initializing variables here and in the Initialize function. constructor() public { owner = msg.sender; setupStates(); player1 = address(0); player2 = address(0); winner = address(0); ethrReg = address(0); gameReg = address(0); playerTurn = address(0); betAmt = 0; timeout = 2**256 - 1; timeoutInterval = 1 days; fairGame = false; } // EVENTS event ValidSigner(address player, address signer, bool result); event JoinedGame(address player, string message); event StateMove(address player, uint shot); event StateChanged(string newState); event RevealedBoard(address player, uint blockNum); event GameEnded(address winner); event TimeoutStarted(uint timestamp); event TimeoutReseted(uint timestamp); event BetClaimed(address player, uint amount, uint timestamp); // MODIFIERS modifier ifPlayer() { require(player1 != address(0) && player2 != address(0),", players not set."); require(msg.sender == player1 || msg.sender == player2, ", not a valid player."); _; } modifier ifOwner() { if(msg.sender == owner) { _; } else { revert(", not game contract owner."); } } /* EXTERNAL FUNCTIONS */ /// @dev Get the final revealed board. /// @param _player The address of the selected player. /// @return Board array. function getPlayerShips(address _player) external view returns(uint[]){ uint[] storage board = playerShips[_player]; return board; } /// @dev Get topic for whisper channel if joined as player. /// @return String topic. function getTopic() external view ifPlayer returns(string){ return topic; } /// @dev Initialize registries addresses. /// @param _ethrReg The address of the Ethr DID registry. /// @param _gameReg The address of the Game registry. function initialize(address _ethrReg, address _gameReg) external isInitializer ifOwner{ require(gameReg == address(0) && ethrReg == address(0), ", registry already set."); ethrReg = _ethrReg; gameReg = _gameReg; } /// @dev Claim bet if the player is the winner. By expired timeout or moves. function claimBet() external checkAllowed ifPlayer { if(block.timestamp >= timeout && msg.sender == opponent(playerTurn)){ winner = opponent(playerTurn); require(gameReg.call(REGISTRY_WINNER_FSIG, abi.encode(winner))); } if(msg.sender == winner) { winner.transfer(address(this).balance); emit BetClaimed(msg.sender, address(this).balance, block.timestamp); } else { revert("... You are a loser :( "); } } /* PUBLIC FUNCTIONS */ /// @dev Fallback function function () public { revert(); } /// @dev Join the game and set the bet. Player 1 is set by factory contract. /// @dev Player 2 can join later or be set at creation time. /// @param _playerA Player 1 address. /// @param _playerB Player 2 address. /// @param _topic Whisper-channel topic. function joinGame(address _playerA, address _playerB, string _topic) public payable checkAllowed { require(gameReg != address(0), ", game registry not set."); require(_playerA != owner && _playerB != owner, ", factory contract cannot play."); require(msg.value >= betAmt,", invalid bet amount."); // The Factory is the contract owner and cannot register as player. if( _playerA != address(0) && player1 == address(0) && msg.sender == owner){ player1 = _playerA; topic = _topic; betAmt = msg.value; // Set the contract address as game owner. require(gameReg.call(REGISTRY_GAME_OWNER_FSIG)); // Set player1 in registry. require(gameReg.call(REGISTRY_PLAYERS_FSIG, abi.encode(player1,msg.value,1))); emit JoinedGame(player1, "Player1"); } // Validate if _playerB parameter is set. if( _playerB != address(0) && player2 == address(0) && _playerB != player1){ player2 = _playerB; require(gameReg.call(REGISTRY_PLAYERS_FSIG, abi.encode(player2,msg.value,2))); } hiddenShips[msg.sender] = bytes32(0); playerSigner[msg.sender] = address(0); // Join as player 2 if not set in parameter, place the correct bet. if(player2 == address(0) && msg.sender != player1 && msg.sender != owner){ require(msg.value == betAmt, ", player2 incorrect bet amount."); player2 = msg.sender; } // Player 2 was passed as parameter without bet. if(msg.sender == player2){ require(msg.value == betAmt, ", player2 incorrect bet amount."); playerTurn = player2; require(gameReg.call(REGISTRY_PLAYERS_FSIG, abi.encode(player2,msg.value,2))); emit JoinedGame(msg.sender, "Player2"); } // If not a VIP identity, get out. if( !(msg.sender == owner || msg.sender == player1 || msg.sender == player2)){ revert(", not a VIP identity."); } } /// @dev Set the hash of your board. /// @param _shipsHash The player's grid hash. /// @param _sig Message signature to get signer. function setHiddenShips(bytes32 _shipsHash, bytes _sig) public checkAllowed ifPlayer { require(_shipsHash != bytes32(0) && _sig.length == 65); require(hiddenShips[msg.sender] == bytes32(0) || playerSigner[msg.sender] == address(0)); //Get signer delegate from board signature. _shipsHash is keccak256(board[], secret, gameAddress) address signer = ECRecovery.recover(_shipsHash.toEthSignedMessageHash(),_sig); //Validate signer delegate from Ethr registry. Secp256k1VerificationKey2018 -> "veriKey" bool result = isValidDelegate(msg.sender, "veriKey", signer, ethrReg); require(result == true, ", not a valid ethr signer delegate."); emit ValidSigner(msg.sender, signer, result); hiddenShips[msg.sender] = _shipsHash; playerSigner[msg.sender] = signer; } /// @dev Used to start timeout or recreate game history for last dispute resolution. State moves need to be ordered by nonce. /// @param _xy player's move. /// @param _nonce sequence of game moves. /// @param _sig player's signature. /// @param _replySig opponent's signature on agreed player's move. function stateMove(uint _xy, uint _nonce, address _nextTurn, bytes _sig, bytes _replySig) public checkAllowed ifPlayer { require(_sig.length == 65 && _replySig.length == 65,", incorrect signature size"); require(_xy >= 0 && _xy <= 99,", out of range shot."); require(_nonce == nonce, ", incorrect nonce number."); require(_nonce >= 0 && _nonce <= 200, ", out of range nonce."); address player; bytes32 hash = keccak256(abi.encodePacked(_xy, _nonce, address(this))); address signer = ECRecovery.recover(hash.toEthSignedMessageHash(), _sig); if(signer == playerSigner[player1]){ player = player1; }else if(signer == playerSigner[player2]){ player = player2; }else { revert(", invalid signer."); } bytes32 replyHash = keccak256(abi.encodePacked(hash, _nonce, _nextTurn, address(this))); address replySigner = ECRecovery.recover(replyHash.toEthSignedMessageHash(), _replySig); require(replySigner == playerSigner[opponent(player)], ", invalid replySigner."); nonce = _nonce + 1; playerTurn = _nextTurn; if(msg.sender == opponent(playerTurn)){ startTimeout(); }else{ resetTimeout(); } playerMoves[player].push(_xy); emit StateMove(player, _xy); } /// @dev Reveal my board. /// @param _ships The player's board. /// @param _secret Player's secret. function revealMyBoard(uint[] _ships, uint[] _hits, uint[] _notHits, bytes4 _secret) public checkAllowed ifPlayer { require(_ships.length == 20,", incorrect ships input lenght."); require(_hits.length > 0 && _hits.length <= 20 && _notHits.length > 0 && _notHits.length <= 80,", incorrect revealed board size."); require(_secret != bytes4(0), ", incorrect secret type."); require(hiddenShips[msg.sender] != bytes32(0) && playerSigner[msg.sender] != address(0)); require(hiddenShips[opponent(msg.sender)] != bytes32(0) && playerSigner[opponent(msg.sender)] != address(0)); //Hash inputs to recreate hidden board. bytes32 hash = keccak256(abi.encodePacked(_ships, _secret, address(this))); require(hash == hiddenShips[msg.sender], ", invalid revealed board."); secret[msg.sender] == _secret; uint i; for(i = 0; i < 20; i++){ playerShips[msg.sender].push(_ships[i]); } // _hits length > 0 and <= 20 for(i = 0; i < _hits.length; i++){ hitsToPlayer[msg.sender].push(_hits[i]); } // _notHits length > 0 and <= 80 for(i = 0; i < _notHits.length; i++){ notHitsToPlayer[msg.sender].push(_notHits[i]); } emit RevealedBoard(msg.sender, block.timestamp); } /// @dev Reveal played board. function revealOtherBoard(uint[] _hits, uint[] _notHits) public checkAllowed ifPlayer { require(_hits.length > 0 && _hits.length <= 20 && _notHits.length > 0 && _notHits.length <= 80,", incorrect revealed board size."); require(hiddenShips[msg.sender] != bytes32(0) && playerSigner[msg.sender] != address(0)); require(hiddenShips[opponent(msg.sender)] != bytes32(0) && playerSigner[opponent(msg.sender)] != address(0)); address playerAddrHash = Bytes.toAddress(keccak256(abi.encodePacked(msg.sender))); uint i; // _hits length > 0 and <= 20 for(i = 0; i < _hits.length; i++){ hitsToPlayer[playerAddrHash].push(_hits[i]); } // _notHits length > 0 and <= 80 for(i = 0; i < _notHits.length; i++){ notHitsToPlayer[playerAddrHash].push(_notHits[i]); } emit RevealedBoard(playerAddrHash, block.timestamp); } /// @dev Claim victory. Boards need to be revealed and match. Use stateMove in case of cheaters. function claimVictory() public checkAllowed ifPlayer { uint[] storage Board1 = playerShips[msg.sender]; uint[] storage Board2 = playerShips[opponent(msg.sender)]; require(Board1.length == 20 && Board2.length == 20,", invalid revealed board size."); uint requiredToWin = 20; address player; address playerOpponentHash; playerOpponentHash = Bytes.toAddress(keccak256(abi.encodePacked(opponent(player1)))); bytes32 hash1 = keccak256(abi.encodePacked(hitsToPlayer[player1])); bytes32 hash2 = keccak256(abi.encodePacked(hitsToPlayer[playerOpponentHash])); bytes32 hash3 = keccak256(abi.encodePacked(notHitsToPlayer[player1])); bytes32 hash4 = keccak256(abi.encodePacked(notHitsToPlayer[playerOpponentHash])); playerOpponentHash = Bytes.toAddress(keccak256(abi.encodePacked(opponent(player2)))); bytes32 hash5 = keccak256(abi.encodePacked(hitsToPlayer[player2])); bytes32 hash6 = keccak256(abi.encodePacked(hitsToPlayer[playerOpponentHash])); bytes32 hash7 = keccak256(abi.encodePacked(notHitsToPlayer[player2])); bytes32 hash8 = keccak256(abi.encodePacked(notHitsToPlayer[playerOpponentHash])); if((hash1 == hash2) && (hash3 == hash4) && (hash5 == hash6) && (hash7 == hash8)){ fairGame = true; } else{ fairGame = false; } //hitsToPlayer[opponent(msg.sender)].lenght == requiredToWin; //winner = msg.sender; //require(gameReg.call(bytes4(keccak256("setWinner(address)")), abi.encode(winner))); } /* INTERNAL FUNCTIONS */ /// @dev Start timeout in case of game halt. function startTimeout() internal ifPlayer { timeout = block.timestamp + timeoutInterval; emit TimeoutStarted(block.timestamp); } /// @dev Set timeout to initial state. function resetTimeout() internal ifPlayer { timeout = 2**256 - 1; emit TimeoutReseted(block.timestamp); } /// @dev Allow functions in the given state. function setupStates() internal { setStates(states); allowFunction(STATE1, this.joinGame.selector); //"Create" allowFunction(STATE2, this.setHiddenShips.selector); //"Set" allowFunction(STATE3, this.stateMove.selector); //"Play" allowFunction(STATE3, this.revealMyBoard.selector); //"Play" allowFunction(STATE4, this.stateMove.selector); //"GameOver" allowFunction(STATE4, this.revealMyBoard.selector); //"GameOver" allowFunction(STATE4, this.revealOtherBoard.selector);//"GameOver" allowFunction(STATE4, this.claimVictory.selector); //"GameOver" allowFunction(STATE4, this.claimBet.selector); //"GameOver" addStartCondition(STATE2, verifyPlayers); //"Set" addStartCondition(STATE3, verifyBoard); //"Play" addStartCondition(STATE4, verifyRevealedBoards); //"GameOver" addStartCondition(STATE4, verifyWinner); //"GameOver" addStartCondition(STATE4, verifyTimeout); //"GameOver" } /// @dev Verify player conditions to transition to next state. /// @return If conditions met returns true. function verifyPlayers(bytes32) internal returns(bool){ if(playerTurn == player2 && player1 != address(0) && player2 != address(0)){ emit StateChanged("Set"); return true; } else { return false; } } /// @dev Verify boards ready conditions to transition to next state. /// @return If conditions met returns true. function verifyBoard(bytes32) internal returns(bool){ if( hiddenShips[player1] != bytes32(0) && hiddenShips[player2] != bytes32(0) && playerSigner[player1] != address(0) && playerSigner[player2] != address(0) ){ emit StateChanged("Play"); return true; }else{ return false; } } /// @dev Verify revealed boards conditions to transition to next state. /// @return If conditions met returns true. function verifyRevealedBoards(bytes32) internal returns(bool){ if(playerShips[player1].length > 0 || playerShips[player2].length > 0){ emit StateChanged("GameOver"); return true; }else { return false; } } /// @dev Verify winner player conditions to transition to next state. /// @return If conditions met returns true. function verifyWinner(bytes32) internal returns(bool){ if(winner != address(0)){ emit StateChanged("GameOver"); emit GameEnded(winner); return true; }else { return false; } } /// @dev Verify timeout to finalize game. /// @return If conditions met returns true. function verifyTimeout(bytes32) internal returns(bool){ if(block.timestamp >= timeout){ emit StateChanged("GameOver"); return true; }else { return false; } } /// @dev Get the opponent player. /// @param _player The address of the selected player to find out who the opponent is. /// @return Address of the opponent player. function opponent(address _player) internal view returns (address) { require(player2 != address(0), ", game has not started."); if (_player == player1) { return player2; } else if (_player == player2) { return player1; } else { revert(", invalid opponent player."); } } /// @dev Verifies if the signer delegate is valid in the Ethr DID registry. /// @param _identity The address owner. /// @param _delegateType Type of delegate. Signer -> Secp256k1VerificationKey2018 -> bytes32("veriKey"). /// @param _delegate The address of the signer delegate. /// @param _registry The address of the Ethr DID registry. function isValidDelegate( address _identity, string _delegateType, address _delegate, address _registry ) internal ifPlayer view returns(bool result){ require(ethrReg != address(0), ", ethr registry not set."); require(_identity != address(0) && bytes(_delegateType).length > 0 && _delegate != address(0),", invalid delegate input."); bytes memory data = abi.encodeWithSignature("validDelegate(address,bytes32,address)", _identity, Bytes.stringToBytes32(_delegateType), _delegate); /* solium-disable-next-line security/no-inline-assembly */ assembly { let ptr := mload(0x40) let success := staticcall(sub(gas, 3800), _registry, add(data, 0x20), mload(data), ptr, 0x20) if eq(success, 0) { revert(0, 0) } result := mload(ptr) } } }
Get topic for whisper channel if joined as player. return String topic.
function getTopic() external view ifPlayer returns(string){ return topic; }
1,824,974
./full_match/1/0x2dc92A6Af044426A438BBB3ebFC3e6A04B00d1Fa/sources/contracts/erc721a/DropCollection.sol
The following functions are overrides required by Solidity. See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721AUpgradeable, IERC721AUpgradeable, BaseCollection) returns (bool) { return ERC721AUpgradeable.supportsInterface(interfaceId) || BaseCollection.supportsInterface(interfaceId) || super.supportsInterface(interfaceId); }
16,531,319
pragma solidity ^0.4.24; /** * @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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } library Attribute { enum AttributeType { ROLE_MANAGER, // 0 ROLE_OPERATOR, // 1 IS_BLACKLISTED, // 2 HAS_PASSED_KYC_AML, // 3 NO_FEES, // 4 /* Additional user-defined later */ USER_DEFINED } function toUint256(AttributeType _type) internal pure returns (uint256) { return uint256(_type); } } /** * @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; } } library BitManipulation { uint256 constant internal ONE = uint256(1); function setBit(uint256 _num, uint256 _pos) internal pure returns (uint256) { return _num | (ONE << _pos); } function clearBit(uint256 _num, uint256 _pos) internal pure returns (uint256) { return _num & ~(ONE << _pos); } function toggleBit(uint256 _num, uint256 _pos) internal pure returns (uint256) { return _num ^ (ONE << _pos); } function checkBit(uint256 _num, uint256 _pos) internal pure returns (bool) { return (_num >> _pos & ONE == ONE); } } /** * @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 Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Claimable Ex * @dev Extension for the Claimable contract, where the ownership transfer can be canceled. */ contract ClaimableEx is Claimable { /* * @dev Cancels the ownership transfer. */ function cancelOwnershipTransfer() onlyOwner public { pendingOwner = owner; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this Ether. * @notice Ether can still be sent to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by setting a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param _from address The address that is transferring the tokens * @param _value uint256 the amount of the specified token * @param _data Bytes The data passed from the caller. */ function tokenFallback( address _from, uint256 _value, bytes _data ) external pure { _from; _value; _data; revert(); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param _contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address _contractAddr) external onlyOwner { Ownable contractInst = Ownable(_contractAddr); contractInst.transferOwnership(owner); } } /** * @title Base contract for contracts that should not own things. * @author Remco Bloemen <remco@2π.com> * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or * Owned contracts. See respective base contracts for details. */ contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } /** * @title NoOwner Ex * @dev Extension for the NoOwner contract, to support a case where * this contract's owner can't own ether or tokens. * Note that we *do* inherit reclaimContract from NoOwner: This contract * does have to own contracts, but it also has to be able to relinquish them **/ contract NoOwnerEx is NoOwner { function reclaimEther(address _to) external onlyOwner { _to.transfer(address(this).balance); } function reclaimToken(ERC20Basic token, address _to) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(_to, balance); } } /** * @title Address Set. * @dev This contract allows to store addresses in a set and * owner can run a loop through all elements. **/ contract AddressSet is Ownable { mapping(address => bool) exist; address[] elements; /** * @dev Adds a new address to the set. * @param _addr Address to add. * @return True if succeed, otherwise false. */ function add(address _addr) onlyOwner public returns (bool) { if (contains(_addr)) { return false; } exist[_addr] = true; elements.push(_addr); return true; } /** * @dev Checks whether the set contains a specified address or not. * @param _addr Address to check. * @return True if the address exists in the set, otherwise false. */ function contains(address _addr) public view returns (bool) { return exist[_addr]; } /** * @dev Gets an element at a specified index in the set. * @param _index Index. * @return A relevant address. */ function elementAt(uint256 _index) onlyOwner public view returns (address) { require(_index < elements.length); return elements[_index]; } /** * @dev Gets the number of elements in the set. * @return The number of elements. */ function getTheNumberOfElements() onlyOwner public view returns (uint256) { return elements.length; } } // A wrapper around the balances mapping. contract BalanceSheet is ClaimableEx { using SafeMath for uint256; mapping (address => uint256) private balances; AddressSet private holderSet; constructor() public { holderSet = new AddressSet(); } /** * @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]; } function addBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = balances[_addr].add(_value); _checkHolderSet(_addr); } function subBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = balances[_addr].sub(_value); } function setBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = _value; _checkHolderSet(_addr); } function setBalanceBatch( address[] _addrs, uint256[] _values ) public onlyOwner { uint256 _count = _addrs.length; require(_count == _values.length); for(uint256 _i = 0; _i < _count; _i++) { setBalance(_addrs[_i], _values[_i]); } } function getTheNumberOfHolders() public view returns (uint256) { return holderSet.getTheNumberOfElements(); } function getHolder(uint256 _index) public view returns (address) { return holderSet.elementAt(_index); } function _checkHolderSet(address _addr) internal { if (!holderSet.contains(_addr)) { holderSet.add(_addr); } } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * A version of OpenZeppelin's StandardToken whose balances mapping has been replaced * with a separate BalanceSheet contract. Most useful in combination with e.g. * HasNoContracts because then it can relinquish its balance sheet to a new * version of the token, removing the need to copy over balances. **/ contract StandardToken is ClaimableEx, NoOwnerEx, ERC20 { using SafeMath for uint256; uint256 totalSupply_; BalanceSheet private balances; event BalanceSheetSet(address indexed sheet); mapping (address => mapping (address => uint256)) private allowed; constructor() public { totalSupply_ = 0; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances.balanceOf(_owner); } /** * @dev Claim ownership of the BalanceSheet contract * @param _sheet The address of the BalanceSheet to claim. */ function setBalanceSheet(address _sheet) public onlyOwner returns (bool) { balances = BalanceSheet(_sheet); balances.claimOwnership(); emit BalanceSheetSet(_sheet); return true; } function getTheNumberOfHolders() public view returns (uint256) { return balances.getTheNumberOfHolders(); } function getHolder(uint256 _index) public view returns (address) { return balances.getHolder(_index); } /** * @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) { _transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { _transferFrom(_from, _to, _value, msg.sender); 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) { _approve(_spender, _value, msg.sender); 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) * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { _increaseApproval(_spender, _addedValue, msg.sender); 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) * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { _decreaseApproval(_spender, _subtractedValue, msg.sender); return true; } function _approve( address _spender, uint256 _value, address _tokenHolder ) internal { allowed[_tokenHolder][_spender] = _value; emit Approval(_tokenHolder, _spender, _value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _burner The account whose tokens will be burnt. * @param _value The amount that will be burnt. */ function _burn(address _burner, uint256 _value) internal { require(_burner != 0); require(_value <= balanceOf(_burner), "not enough balance to burn"); // 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.subBalance(_burner, _value); totalSupply_ = totalSupply_.sub(_value); emit Transfer(_burner, address(0), _value); } function _decreaseApproval( address _spender, uint256 _subtractedValue, address _tokenHolder ) internal { uint256 _oldValue = allowed[_tokenHolder][_spender]; if (_subtractedValue >= _oldValue) { allowed[_tokenHolder][_spender] = 0; } else { allowed[_tokenHolder][_spender] = _oldValue.sub(_subtractedValue); } emit Approval(_tokenHolder, _spender, allowed[_tokenHolder][_spender]); } function _increaseApproval( address _spender, uint256 _addedValue, address _tokenHolder ) internal { allowed[_tokenHolder][_spender] = ( allowed[_tokenHolder][_spender].add(_addedValue)); emit Approval(_tokenHolder, _spender, allowed[_tokenHolder][_spender]); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances.addBalance(_account, _amount); emit Transfer(address(0), _account, _amount); } function _transfer(address _from, address _to, uint256 _value) internal { require(_to != address(0), "to address cannot be 0x0"); require(_from != address(0),"from address cannot be 0x0"); require(_value <= balanceOf(_from), "not enough balance to transfer"); // SafeMath.sub will throw if there is not enough balance. balances.subBalance(_from, _value); balances.addBalance(_to, _value); emit Transfer(_from, _to, _value); } function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal { uint256 _allowed = allowed[_from][_spender]; require(_value <= _allowed, "not enough allowance to transfer"); allowed[_from][_spender] = allowed[_from][_spender].sub(_value); _transfer(_from, _to, _value); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). **/ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value, string note); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. * @param _note a note that burner can attach. */ function burn(uint256 _value, string _note) public returns (bool) { _burn(msg.sender, _value, _note); return true; } /** * @dev Burns a specific amount of tokens of an user. * @param _burner Who has tokens to be burned. * @param _value The amount of tokens to be burned. * @param _note a note that the manager can attach. */ function _burn( address _burner, uint256 _value, string _note ) internal { _burn(_burner, _value); emit Burn(_burner, _value, _note); } } // Interface for logic governing write access to a Registry. contract RegistryAccessManager { // Called when _admin attempts to write _value for _who's _attribute. // Returns true if the write is allowed to proceed. function confirmWrite( address _who, Attribute.AttributeType _attribute, address _admin ) public returns (bool); } contract DefaultRegistryAccessManager is RegistryAccessManager { function confirmWrite( address /*_who*/, Attribute.AttributeType _attribute, address _operator ) public returns (bool) { Registry _client = Registry(msg.sender); if (_operator == _client.owner()) { return true; } else if (_client.hasAttribute(_operator, Attribute.AttributeType.ROLE_MANAGER)) { return (_attribute == Attribute.AttributeType.ROLE_OPERATOR); } else if (_client.hasAttribute(_operator, Attribute.AttributeType.ROLE_OPERATOR)) { return (_attribute != Attribute.AttributeType.ROLE_OPERATOR && _attribute != Attribute.AttributeType.ROLE_MANAGER); } } } contract Registry is ClaimableEx { using BitManipulation for uint256; struct AttributeData { uint256 value; } // Stores arbitrary attributes for users. An example use case is an ERC20 // token that requires its users to go through a KYC/AML check - in this case // a validator can set an account's "hasPassedKYC/AML" attribute to 1 to indicate // that account can use the token. This mapping stores that value (1, in the // example) as well as which validator last set the value and at what time, // so that e.g. the check can be renewed at appropriate intervals. mapping(address => AttributeData) private attributes; // The logic governing who is allowed to set what attributes is abstracted as // this accessManager, so that it may be replaced by the owner as needed. RegistryAccessManager public accessManager; event SetAttribute( address indexed who, Attribute.AttributeType attribute, bool enable, string notes, address indexed adminAddr ); event SetManager( address indexed oldManager, address indexed newManager ); constructor() public { accessManager = new DefaultRegistryAccessManager(); } // Writes are allowed only if the accessManager approves function setAttribute( address _who, Attribute.AttributeType _attribute, string _notes ) public { bool _canWrite = accessManager.confirmWrite( _who, _attribute, msg.sender ); require(_canWrite); // Get value of previous attribute before setting new attribute uint256 _tempVal = attributes[_who].value; attributes[_who] = AttributeData( _tempVal.setBit(Attribute.toUint256(_attribute)) ); emit SetAttribute(_who, _attribute, true, _notes, msg.sender); } function clearAttribute( address _who, Attribute.AttributeType _attribute, string _notes ) public { bool _canWrite = accessManager.confirmWrite( _who, _attribute, msg.sender ); require(_canWrite); // Get value of previous attribute before setting new attribute uint256 _tempVal = attributes[_who].value; attributes[_who] = AttributeData( _tempVal.clearBit(Attribute.toUint256(_attribute)) ); emit SetAttribute(_who, _attribute, false, _notes, msg.sender); } // Returns true if the uint256 value stored for this attribute is non-zero function hasAttribute( address _who, Attribute.AttributeType _attribute ) public view returns (bool) { return attributes[_who].value.checkBit(Attribute.toUint256(_attribute)); } // Returns the exact value of the attribute, as well as its metadata function getAttributes( address _who ) public view returns (uint256) { AttributeData memory _data = attributes[_who]; return _data.value; } function setManager(RegistryAccessManager _accessManager) public onlyOwner { emit SetManager(accessManager, _accessManager); accessManager = _accessManager; } } // Superclass for contracts that have a registry that can be set by their owners contract HasRegistry is Ownable { Registry public registry; event SetRegistry(address indexed registry); function setRegistry(Registry _registry) public onlyOwner { registry = _registry; emit SetRegistry(registry); } } /** * @title Manageable * @dev The Manageable contract provides basic authorization control functions * for managers. This simplifies the implementation of "manager permissions". */ contract Manageable is HasRegistry { /** * @dev Throws if called by any account that is not in the managers list. */ modifier onlyManager() { require( registry.hasAttribute( msg.sender, Attribute.AttributeType.ROLE_MANAGER ) ); _; } /** * @dev Getter to determine if address is a manager */ function isManager(address _operator) public view returns (bool) { return registry.hasAttribute( _operator, Attribute.AttributeType.ROLE_MANAGER ); } } // Interface implemented by tokens that are the *target* of a BurnableToken's // delegation. That is, if we want to replace BurnableToken X by // Y but for convenience we'd like users of X // to be able to keep using it and it will just forward calls to Y, // then X should extend CanDelegate and Y should extend DelegateBurnable. // Most ERC20 calls use the value of msg.sender to figure out e.g. whose // balance to update; since X becomes the msg.sender of all such calls // that it forwards to Y, we add the origSender parameter to those calls. // Delegation is intended as a convenience for legacy users of X since // we do not expect all regular users to learn about Y and change accordingly, // but we do require the *owner* of X to now use Y instead so ownerOnly // functions are not delegated and should be disabled instead. // This delegation system is intended to work with the modified versions of // the standard ERC20 token contracts, allowing the balances // to be moved over to a new contract. // NOTE: To maintain backwards compatibility, these function signatures // cannot be changed contract DelegateBurnable { function delegateTotalSupply() public view returns (uint256); function delegateBalanceOf(address _who) public view returns (uint256); function delegateTransfer(address _to, uint256 _value, address _origSender) public returns (bool); function delegateAllowance(address _owner, address _spender) public view returns (uint256); function delegateTransferFrom( address _from, address _to, uint256 _value, address _origSender ) public returns (bool); function delegateApprove( address _spender, uint256 _value, address _origSender ) public returns (bool); function delegateIncreaseApproval( address _spender, uint256 _addedValue, address _origSender ) public returns (bool); function delegateDecreaseApproval( address _spender, uint256 _subtractedValue, address _origSender ) public returns (bool); function delegateBurn( address _origSender, uint256 _value, string _note ) public; function delegateGetTheNumberOfHolders() public view returns (uint256); function delegateGetHolder(uint256 _index) public view returns (address); } /** * @title Contactable token * @dev Basic version of a contactable contract, allowing the owner to provide a string with their * contact information. */ contract Contactable is Ownable { string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param _info The contact information to attach to the contract. */ function setContactInformation(string _info) public onlyOwner { contactInformation = _info; } } /** * @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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function _transfer( address _from, address _to, uint256 _value ) internal whenNotPaused { super._transfer(_from, _to, _value); } function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal whenNotPaused { super._transferFrom(_from, _to, _value, _spender); } function _approve( address _spender, uint256 _value, address _tokenHolder ) internal whenNotPaused { super._approve(_spender, _value, _tokenHolder); } function _increaseApproval( address _spender, uint256 _addedValue, address _tokenHolder ) internal whenNotPaused { super._increaseApproval(_spender, _addedValue, _tokenHolder); } function _decreaseApproval( address _spender, uint256 _subtractedValue, address _tokenHolder ) internal whenNotPaused { super._decreaseApproval(_spender, _subtractedValue, _tokenHolder); } function _burn( address _burner, uint256 _value ) internal whenNotPaused { super._burn(_burner, _value); } } // See DelegateBurnable.sol for more on the delegation system. contract CanDelegateToken is BurnableToken { // If this contract needs to be upgraded, the new contract will be stored // in 'delegate' and any BurnableToken calls to this contract will be delegated to that one. DelegateBurnable public delegate; event DelegateToNewContract(address indexed newContract); // Can undelegate by passing in _newContract = address(0) function delegateToNewContract( DelegateBurnable _newContract ) public onlyOwner { delegate = _newContract; emit DelegateToNewContract(delegate); } // If a delegate has been designated, all ERC20 calls are forwarded to it function _transfer(address _from, address _to, uint256 _value) internal { if (!_hasDelegate()) { super._transfer(_from, _to, _value); } else { require(delegate.delegateTransfer(_to, _value, _from)); } } function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal { if (!_hasDelegate()) { super._transferFrom(_from, _to, _value, _spender); } else { require(delegate.delegateTransferFrom(_from, _to, _value, _spender)); } } function totalSupply() public view returns (uint256) { if (!_hasDelegate()) { return super.totalSupply(); } else { return delegate.delegateTotalSupply(); } } function balanceOf(address _who) public view returns (uint256) { if (!_hasDelegate()) { return super.balanceOf(_who); } else { return delegate.delegateBalanceOf(_who); } } function getTheNumberOfHolders() public view returns (uint256) { if (!_hasDelegate()) { return super.getTheNumberOfHolders(); } else { return delegate.delegateGetTheNumberOfHolders(); } } function getHolder(uint256 _index) public view returns (address) { if (!_hasDelegate()) { return super.getHolder(_index); } else { return delegate.delegateGetHolder(_index); } } function _approve( address _spender, uint256 _value, address _tokenHolder ) internal { if (!_hasDelegate()) { super._approve(_spender, _value, _tokenHolder); } else { require(delegate.delegateApprove(_spender, _value, _tokenHolder)); } } function allowance( address _owner, address _spender ) public view returns (uint256) { if (!_hasDelegate()) { return super.allowance(_owner, _spender); } else { return delegate.delegateAllowance(_owner, _spender); } } function _increaseApproval( address _spender, uint256 _addedValue, address _tokenHolder ) internal { if (!_hasDelegate()) { super._increaseApproval(_spender, _addedValue, _tokenHolder); } else { require( delegate.delegateIncreaseApproval(_spender, _addedValue, _tokenHolder) ); } } function _decreaseApproval( address _spender, uint256 _subtractedValue, address _tokenHolder ) internal { if (!_hasDelegate()) { super._decreaseApproval(_spender, _subtractedValue, _tokenHolder); } else { require( delegate.delegateDecreaseApproval( _spender, _subtractedValue, _tokenHolder) ); } } function _burn(address _burner, uint256 _value, string _note) internal { if (!_hasDelegate()) { super._burn(_burner, _value, _note); } else { delegate.delegateBurn(_burner, _value , _note); } } function _hasDelegate() internal view returns (bool) { return !(delegate == address(0)); } } // Treats all delegate functions exactly like the corresponding normal functions, // e.g. delegateTransfer is just like transfer. See DelegateBurnable.sol for more on // the delegation system. contract DelegateToken is DelegateBurnable, BurnableToken { address public delegatedFrom; event DelegatedFromSet(address addr); // Only calls from appointed address will be processed modifier onlyMandator() { require(msg.sender == delegatedFrom); _; } function setDelegatedFrom(address _addr) public onlyOwner { delegatedFrom = _addr; emit DelegatedFromSet(_addr); } // each function delegateX is simply forwarded to function X function delegateTotalSupply( ) public onlyMandator view returns (uint256) { return totalSupply(); } function delegateBalanceOf( address _who ) public onlyMandator view returns (uint256) { return balanceOf(_who); } function delegateTransfer( address _to, uint256 _value, address _origSender ) public onlyMandator returns (bool) { _transfer(_origSender, _to, _value); return true; } function delegateAllowance( address _owner, address _spender ) public onlyMandator view returns (uint256) { return allowance(_owner, _spender); } function delegateTransferFrom( address _from, address _to, uint256 _value, address _origSender ) public onlyMandator returns (bool) { _transferFrom(_from, _to, _value, _origSender); return true; } function delegateApprove( address _spender, uint256 _value, address _origSender ) public onlyMandator returns (bool) { _approve(_spender, _value, _origSender); return true; } function delegateIncreaseApproval( address _spender, uint256 _addedValue, address _origSender ) public onlyMandator returns (bool) { _increaseApproval(_spender, _addedValue, _origSender); return true; } function delegateDecreaseApproval( address _spender, uint256 _subtractedValue, address _origSender ) public onlyMandator returns (bool) { _decreaseApproval(_spender, _subtractedValue, _origSender); return true; } function delegateBurn( address _origSender, uint256 _value, string _note ) public onlyMandator { _burn(_origSender, _value , _note); } function delegateGetTheNumberOfHolders() public view returns (uint256) { return getTheNumberOfHolders(); } function delegateGetHolder(uint256 _index) public view returns (address) { return getHolder(_index); } } /** * @title Asset information. * @dev Stores information about a specified real asset. */ contract AssetInfo is Manageable { string public publicDocument; /** * Event for updated running documents logging. * @param newLink New link. */ event UpdateDocument( string newLink ); /** * @param _publicDocument A link to a zip file containing running documents of the asset. */ constructor(string _publicDocument) public { publicDocument = _publicDocument; } /** * @dev Updates information about where to find new running documents of this asset. * @param _link A link to a zip file containing running documents of the asset. */ function setPublicDocument(string _link) public onlyManager { publicDocument = _link; emit UpdateDocument(publicDocument); } } /** * @title BurnableExToken. * @dev Extension for the BurnableToken contract, to support * some manager to enforce burning all tokens of all holders. **/ contract BurnableExToken is Manageable, BurnableToken { /** * @dev Burns all remaining tokens of all holders. * @param _note a note that the manager can attach. */ function burnAll(string _note) external onlyManager { uint256 _holdersCount = getTheNumberOfHolders(); for (uint256 _i = 0; _i < _holdersCount; ++_i) { address _holder = getHolder(_i); uint256 _balance = balanceOf(_holder); if (_balance == 0) continue; _burn(_holder, _balance, _note); } } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation **/ contract MintableToken is StandardToken { event Mint(address indexed to, 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 _value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _value ) public hasMintPermission canMint returns (bool) { _mint(_to, _value); emit Mint(_to, _value); return true; } /** * @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 CompliantToken is HasRegistry, MintableToken { // Addresses can also be blacklisted, preventing them from sending or receiving // PAT tokens. This can be used to prevent the use of PAT by bad actors in // accordance with law enforcement. modifier onlyIfNotBlacklisted(address _addr) { require( !registry.hasAttribute( _addr, Attribute.AttributeType.IS_BLACKLISTED ) ); _; } modifier onlyIfBlacklisted(address _addr) { require( registry.hasAttribute( _addr, Attribute.AttributeType.IS_BLACKLISTED ) ); _; } modifier onlyIfPassedKYC_AML(address _addr) { require( registry.hasAttribute( _addr, Attribute.AttributeType.HAS_PASSED_KYC_AML ) ); _; } function _mint( address _to, uint256 _value ) internal onlyIfPassedKYC_AML(_to) onlyIfNotBlacklisted(_to) { super._mint(_to, _value); } // transfer and transferFrom both call this function, so check blacklist here. function _transfer( address _from, address _to, uint256 _value ) internal onlyIfNotBlacklisted(_from) onlyIfNotBlacklisted(_to) onlyIfPassedKYC_AML(_to) { super._transfer(_from, _to, _value); } } /** * @title TokenWithFees. * @dev This contract allows for transaction fees to be assessed on transfer. **/ contract TokenWithFees is Manageable, StandardToken { uint8 public transferFeeNumerator = 0; uint8 public transferFeeDenominator = 100; // All transaction fees are paid to this address. address public beneficiary; event ChangeWallet(address indexed addr); event ChangeFees(uint8 transferFeeNumerator, uint8 transferFeeDenominator); constructor(address _wallet) public { beneficiary = _wallet; } // transfer and transferFrom both call this function, so pay fee here. // E.g. if A transfers 1000 tokens to B, B will receive 999 tokens, // and the system wallet will receive 1 token. function _transfer(address _from, address _to, uint256 _value) internal { uint256 _fee = _payFee(_from, _value, _to); uint256 _remaining = _value.sub(_fee); super._transfer(_from, _to, _remaining); } function _payFee( address _payer, uint256 _value, address _otherParticipant ) internal returns (uint256) { // This check allows accounts to be whitelisted and not have to pay transaction fees. bool _shouldBeFree = ( registry.hasAttribute(_payer, Attribute.AttributeType.NO_FEES) || registry.hasAttribute(_otherParticipant, Attribute.AttributeType.NO_FEES) ); if (_shouldBeFree) { return 0; } uint256 _fee = _value.mul(transferFeeNumerator).div(transferFeeDenominator); if (_fee > 0) { super._transfer(_payer, beneficiary, _fee); } return _fee; } function checkTransferFee(uint256 _value) public view returns (uint256) { return _value.mul(transferFeeNumerator).div(transferFeeDenominator); } function changeFees( uint8 _transferFeeNumerator, uint8 _transferFeeDenominator ) public onlyManager { require(_transferFeeNumerator < _transferFeeDenominator); transferFeeNumerator = _transferFeeNumerator; transferFeeDenominator = _transferFeeDenominator; emit ChangeFees(transferFeeNumerator, transferFeeDenominator); } /** * @dev Change address of the wallet where the fees will be sent to. * @param _beneficiary The new wallet address. */ function changeWallet(address _beneficiary) public onlyManager { require(_beneficiary != address(0), "new wallet cannot be 0x0"); beneficiary = _beneficiary; emit ChangeWallet(_beneficiary); } } // This allows a token to treat transfer(redeemAddress, value) as burn(value). // This is useful for users of standard wallet programs which have transfer // functionality built in but not the ability to burn. contract WithdrawalToken is BurnableToken { address public constant redeemAddress = 0xfacecafe01facecafe02facecafe03facecafe04; function _transfer(address _from, address _to, uint256 _value) internal { if (_to == redeemAddress) { burn(_value, ''); } else { super._transfer(_from, _to, _value); } } // StandardToken's transferFrom doesn't have to check for _to != redeemAddress, // but we do because we redirect redeemAddress transfers to burns, but // we do not redirect transferFrom function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal { require(_to != redeemAddress, "_to is redeem address"); super._transferFrom(_from, _to, _value, _spender); } } /** * @title PAT token. * @dev PAT is a ERC20 token that: * - has no tokens limit. * - mints new tokens for each new property (real asset). * - can pause and unpause token transfer (and authorization) actions. * - token holders can be distributed profit from asset manager. * - contains real asset information. * - can delegate to a new contract. * - can enforce burning all tokens. * - transferring tokens to 0x0 address is treated as burning. * - transferring tokens with fees are sent to the system wallet. * - attempts to check KYC/AML and Blacklist using Registry. * - attempts to reject ERC20 token transfers to itself and allows token transfer out. * - attempts to reject ether sent and allows any ether held to be transferred out. * - allows the new owner to accept the ownership transfer, the owner can cancel the transfer if needed. **/ contract PATToken is Contactable, AssetInfo, BurnableExToken, CanDelegateToken, DelegateToken, TokenWithFees, CompliantToken, WithdrawalToken, PausableToken { string public name = "RAX Mt.Fuji"; string public symbol = "FUJI"; uint8 public constant decimals = 18; event ChangeTokenName(string newName, string newSymbol); /** * @param _name Name of this token. * @param _symbol Symbol of this token. */ constructor( string _name, string _symbol, string _publicDocument, address _wallet ) public AssetInfo(_publicDocument) TokenWithFees(_wallet) { name = _name; symbol = _symbol; contactInformation = 'https://rax.exchange/'; } function changeTokenName(string _name, string _symbol) public onlyOwner { name = _name; symbol = _symbol; emit ChangeTokenName(_name, _symbol); } /** * @dev Allows the current owner to transfer control of the contract to a new owner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) onlyOwner public { // do not allow self ownership require(_newOwner != address(this)); super.transferOwnership(_newOwner); } }
Change address of the wallet where the fees will be sent to. _beneficiary The new wallet address./
function changeWallet(address _beneficiary) public onlyManager { require(_beneficiary != address(0), "new wallet cannot be 0x0"); beneficiary = _beneficiary; emit ChangeWallet(_beneficiary); }
13,059,921
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; library SafeMath { function ADD802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function ADD802(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, errorMessage); return c; } function SUB29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB29(a, b, "SafeMath: subtraction underflow"); } function SUB29(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL631(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function MUL631(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function DIV549(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV549(a, b, "SafeMath: division by zero"); } function DIV549(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD667(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD667(a, b, "SafeMath: modulo by zero"); } function MOD667(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface IKeep2r { function ADDVOTES925(address voter, uint amount) external; //inject NONSTANDARD NAMING function REMOVEVOTES795(address voter, uint amount) external; //inject NONSTANDARD NAMING function ADDKPRCREDIT324(address job, uint amount) external; //inject NONSTANDARD NAMING function APPROVELIQUIDITY19(address liquidity) external; //inject NONSTANDARD NAMING function REVOKELIQUIDITY95(address liquidity) external; //inject NONSTANDARD NAMING function ADDJOB704(address job) external; //inject NONSTANDARD NAMING function REMOVEJOB261(address job) external; //inject NONSTANDARD NAMING function SETKEEP2RHELPER717(address _kprh) external; //inject NONSTANDARD NAMING function SETGOVERNANCE887(address _governance) external; //inject NONSTANDARD NAMING function ACCEPTGOVERNANCE419() external; //inject NONSTANDARD NAMING function DISPUTE17(address keeper) external; //inject NONSTANDARD NAMING function SLASH754(address bonded, address keeper, uint amount) external; //inject NONSTANDARD NAMING function REVOKE96(address keeper) external; //inject NONSTANDARD NAMING function RESOLVE192(address keeper) external; //inject NONSTANDARD NAMING function GETPRIORVOTES700(address account, uint blockNumber) external view returns (uint); //inject NONSTANDARD NAMING function TOTALBONDED836() external view returns (uint); //inject NONSTANDARD NAMING } contract Governance { using SafeMath for uint; string public constant name820 = "Governance"; //inject NONSTANDARD NAMING uint public _quorumVotes = 5000; // % of total supply required uint public _proposalThreshold = 5000; uint public constant base706 = 10000; //inject NONSTANDARD NAMING function SETQUORUM684(uint quorum_) external { //inject NONSTANDARD NAMING require(msg.sender == address(this), "Governance::setQuorum: timelock only"); require(quorum_ <= base706, "Governance::setQuorum: quorum_ > BASE"); _quorumVotes = quorum_; } function QUORUMVOTES610() public view returns (uint) { //inject NONSTANDARD NAMING return KPR.TOTALBONDED836().MUL631(_quorumVotes).DIV549(base706); } function PROPOSALTHRESHOLD741() public view returns (uint) { //inject NONSTANDARD NAMING return KPR.TOTALBONDED836().MUL631(_proposalThreshold).DIV549(base706); } function SETTHRESHOLD755(uint threshold_) external { //inject NONSTANDARD NAMING require(msg.sender == address(this), "Governance::setQuorum: timelock only"); require(threshold_ <= base706, "Governance::setThreshold: threshold_ > BASE"); _proposalThreshold = threshold_; } function PROPOSALMAXOPERATIONS305() public pure returns (uint) { return 10; } // 10 actions //inject NONSTANDARD NAMING function VOTINGDELAY891() public pure returns (uint) { return 1; } // 1 block //inject NONSTANDARD NAMING function VOTINGPERIOD297() public pure returns (uint) { return 40_320; } // ~7 days in blocks (assuming 15s blocks) //inject NONSTANDARD NAMING IKeep2r immutable public KPR; uint public proposalCount; struct Proposal { uint id; address proposer; uint eta; address[] targets; uint[] values; string[] signatures; bytes[] calldatas; uint startBlock; uint endBlock; uint forVotes; uint againstVotes; bool canceled; bool executed; mapping (address => Receipt) receipts; } struct Receipt { bool hasVoted; bool support; uint votes; } enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } mapping (uint => Proposal) public proposals; mapping (address => uint) public latestProposalIds; bytes32 public constant domain_typehash397 = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); //inject NONSTANDARD NAMING bytes32 public immutable DOMAINSEPARATOR; bytes32 public constant ballot_typehash182 = keccak256("Ballot(uint256 proposalId,bool support)"); //inject NONSTANDARD NAMING event PROPOSALCREATED434(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); //inject NONSTANDARD NAMING event VOTECAST909(address voter, uint proposalId, bool support, uint votes); //inject NONSTANDARD NAMING event PROPOSALCANCELED450(uint id); //inject NONSTANDARD NAMING event PROPOSALQUEUED490(uint id, uint eta); //inject NONSTANDARD NAMING event PROPOSALEXECUTED781(uint id); //inject NONSTANDARD NAMING function PROPOSEJOB470(address job) public { //inject NONSTANDARD NAMING require(msg.sender == address(KPR), "Governance::proposeJob: only VOTER can propose new jobs"); address[] memory targets; targets[0] = address(KPR); string[] memory signatures; signatures[0] = "addJob(address)"; bytes[] memory calldatas; calldatas[0] = abi.encode(job); uint[] memory values; values[0] = 0; _PROPOSE700(targets, values, signatures, calldatas, string(abi.encodePacked("Governance::proposeJob(): ", job))); } function PROPOSE926(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { //inject NONSTANDARD NAMING require(KPR.GETPRIORVOTES700(msg.sender, block.number.SUB29(1)) >= PROPOSALTHRESHOLD741(), "Governance::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "Governance::propose: proposal function information arity mismatch"); require(targets.length != 0, "Governance::propose: must provide actions"); require(targets.length <= PROPOSALMAXOPERATIONS305(), "Governance::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = STATE767(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "Governance::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "Governance::propose: one live proposal per proposer, found an already pending proposal"); } return _PROPOSE700(targets, values, signatures, calldatas, description); } function _PROPOSE700(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) internal returns (uint) { //inject NONSTANDARD NAMING uint startBlock = block.number.ADD802(VOTINGDELAY891()); uint endBlock = startBlock.ADD802(VOTINGPERIOD297()); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit PROPOSALCREATED434(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return newProposal.id; } function QUEUE934(uint proposalId) public { //inject NONSTANDARD NAMING require(STATE767(proposalId) == ProposalState.Succeeded, "Governance::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = block.timestamp.ADD802(delay); for (uint i = 0; i < proposal.targets.length; i++) { _QUEUEORREVERT932(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit PROPOSALQUEUED490(proposalId, eta); } function _QUEUEORREVERT932(address target, uint value, string memory signature, bytes memory data, uint eta) internal { //inject NONSTANDARD NAMING require(!queuedTransactions[keccak256(abi.encode(target, value, signature, data, eta))], "Governance::_queueOrRevert: proposal action already queued at eta"); _QUEUETRANSACTION380(target, value, signature, data, eta); } function EXECUTE292(uint proposalId) public payable { //inject NONSTANDARD NAMING require(guardian == address(0x0) || msg.sender == guardian, "Governance:execute: !guardian"); require(STATE767(proposalId) == ProposalState.Queued, "Governance::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { _EXECUTETRANSACTION42(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit PROPOSALEXECUTED781(proposalId); } function CANCEL285(uint proposalId) public { //inject NONSTANDARD NAMING ProposalState state = STATE767(proposalId); require(state != ProposalState.Executed, "Governance::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(proposal.proposer != address(KPR) && KPR.GETPRIORVOTES700(proposal.proposer, block.number.SUB29(1)) < PROPOSALTHRESHOLD741(), "Governance::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { _CANCELTRANSACTION608(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit PROPOSALCANCELED450(proposalId); } function GETACTIONS567(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { //inject NONSTANDARD NAMING Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function GETRECEIPT636(uint proposalId, address voter) public view returns (Receipt memory) { //inject NONSTANDARD NAMING return proposals[proposalId].receipts[voter]; } function STATE767(uint proposalId) public view returns (ProposalState) { //inject NONSTANDARD NAMING require(proposalCount >= proposalId && proposalId > 0, "Governance::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes.ADD802(proposal.againstVotes) < QUORUMVOTES610()) { return ProposalState.Defeated; } else if (proposal.forVotes <= proposal.againstVotes) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= proposal.eta.ADD802(grace_period471)) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function CASTVOTE458(uint proposalId, bool support) public { //inject NONSTANDARD NAMING _CASTVOTE871(msg.sender, proposalId, support); } function CASTVOTEBYSIG199(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { //inject NONSTANDARD NAMING bytes32 structHash = keccak256(abi.encode(ballot_typehash182, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Governance::castVoteBySig: invalid signature"); _CASTVOTE871(signatory, proposalId, support); } function _CASTVOTE871(address voter, uint proposalId, bool support) internal { //inject NONSTANDARD NAMING require(STATE767(proposalId) == ProposalState.Active, "Governance::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "Governance::_castVote: voter already voted"); uint votes = KPR.GETPRIORVOTES700(voter, proposal.startBlock); if (support) { proposal.forVotes = proposal.forVotes.ADD802(votes); } else { proposal.againstVotes = proposal.againstVotes.ADD802(votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VOTECAST909(voter, proposalId, support, votes); } function GETCHAINID291() internal pure returns (uint) { //inject NONSTANDARD NAMING uint chainId; assembly { chainId := chainid() } return chainId; } event NEWDELAY307(uint indexed newDelay); //inject NONSTANDARD NAMING event CANCELTRANSACTION220(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING event EXECUTETRANSACTION925(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING event QUEUETRANSACTION307(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING uint public constant grace_period471 = 14 days; //inject NONSTANDARD NAMING uint public constant minimum_delay353 = 1 days; //inject NONSTANDARD NAMING uint public constant maximum_delay422 = 30 days; //inject NONSTANDARD NAMING uint public delay = minimum_delay353; address public guardian; address public pendingGuardian; function SETGUARDIAN20(address _guardian) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::setGuardian: !guardian"); pendingGuardian = _guardian; } function ACCEPTGUARDIANSHIP599() external { //inject NONSTANDARD NAMING require(msg.sender == pendingGuardian, "Keep2rGovernance::setGuardian: !pendingGuardian"); guardian = pendingGuardian; } function ADDVOTES925(address voter, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::addVotes: !guardian"); KPR.ADDVOTES925(voter, amount); } function REMOVEVOTES795(address voter, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::removeVotes: !guardian"); KPR.REMOVEVOTES795(voter, amount); } function ADDKPRCREDIT324(address job, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::addKPRCredit: !guardian"); KPR.ADDKPRCREDIT324(job, amount); } function APPROVELIQUIDITY19(address liquidity) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::approveLiquidity: !guardian"); KPR.APPROVELIQUIDITY19(liquidity); } function REVOKELIQUIDITY95(address liquidity) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::revokeLiquidity: !guardian"); KPR.REVOKELIQUIDITY95(liquidity); } function ADDJOB704(address job) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::addJob: !guardian"); KPR.ADDJOB704(job); } function REMOVEJOB261(address job) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::removeJob: !guardian"); KPR.REMOVEJOB261(job); } function SETKEEP2RHELPER717(address kprh) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::setKeep2rHelper: !guardian"); KPR.SETKEEP2RHELPER717(kprh); } function SETGOVERNANCE887(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::setGovernance: !guardian"); KPR.SETGOVERNANCE887(_governance); } function ACCEPTGOVERNANCE419() external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::acceptGovernance: !guardian"); KPR.ACCEPTGOVERNANCE419(); } function DISPUTE17(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::dispute: !guardian"); KPR.DISPUTE17(keeper); } function SLASH754(address bonded, address keeper, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::slash: !guardian"); KPR.SLASH754(bonded, keeper, amount); } function REVOKE96(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::revoke: !guardian"); KPR.REVOKE96(keeper); } function RESOLVE192(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::resolve: !guardian"); KPR.RESOLVE192(keeper); } mapping (bytes32 => bool) public queuedTransactions; constructor(address token_) public { guardian = msg.sender; KPR = IKeep2r(token_); DOMAINSEPARATOR = keccak256(abi.encode(domain_typehash397, keccak256(bytes(name820)), GETCHAINID291(), address(this))); } receive() external payable { } function SETDELAY397(uint delay_) public { //inject NONSTANDARD NAMING require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= minimum_delay353, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= maximum_delay422, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NEWDELAY307(delay); } function _QUEUETRANSACTION380(address target, uint value, string memory signature, bytes memory data, uint eta) internal returns (bytes32) { //inject NONSTANDARD NAMING require(eta >= GETBLOCKTIMESTAMP893().ADD802(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QUEUETRANSACTION307(txHash, target, value, signature, data, eta); return txHash; } function _CANCELTRANSACTION608(address target, uint value, string memory signature, bytes memory data, uint eta) internal { //inject NONSTANDARD NAMING bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CANCELTRANSACTION220(txHash, target, value, signature, data, eta); } function _EXECUTETRANSACTION42(address target, uint value, string memory signature, bytes memory data, uint eta) internal returns (bytes memory) { //inject NONSTANDARD NAMING bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(GETBLOCKTIMESTAMP893() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(GETBLOCKTIMESTAMP893() <= eta.ADD802(grace_period471), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value:value}(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit EXECUTETRANSACTION925(txHash, target, value, signature, data, eta); return returnData; } function GETBLOCKTIMESTAMP893() internal view returns (uint) { //inject NONSTANDARD NAMING // solium-disable-next-line security/no-block-members return block.timestamp; } }
inject NONSTANDARD NAMING
function CASTVOTEBYSIG199(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
12,851,136
//Address: 0x7f0c38d5e951c47d96d3ec96e3127c73ed4b278e //Contract name: OnePay //Balance: 75.873377075 Ether //Verification Date: 2/16/2018 //Transacion Count: 220 // CODE STARTS HERE pragma solidity ^0.4.17; // ERC Token Standard #20 Interface interface ERC20 { // Get the total token supply function totalSupply() public constant returns (uint _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint balance); // Send _value amount of tokens to address _to function transfer(address _to, uint _value) public returns (bool success); // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint _value) public returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint _value) public returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) public constant returns (uint remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint _value); } contract OnePay is ERC20 { // Token basic information string public constant name = "OnePay"; string public constant symbol = "1PAY"; uint256 public constant decimals = 18; // Director address address public director; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping(address => uint256)) allowed; // Public sale control bool public saleClosed; uint256 public currentSalePhase; uint256 public SALE = 9090; // Pre-Sale tokens per eth uint256 public PRE_SALE = 16667; // Sale tokens per eth // Total supply of tokens uint256 public totalSupply; // Total funds received uint256 public totalReceived; // Total amount of coins minted uint256 public mintedCoins; // Hard Cap for the sale uint256 public hardCapSale; // Token Cap uint256 public tokenCap; /** * Functions with this modifier can only be executed by the owner */ modifier onlyDirector() { assert(msg.sender == director); _; } /** * Constructor */ function OnePay() public { // Create the initial director director = msg.sender; // setting the hardCap for sale hardCapSale = 100000000 * 10 ** uint256(decimals); // token Cap tokenCap = 500000000 * 10 ** uint256(decimals); // Set the total supply totalSupply = 0; // Initial sale phase is presale currentSalePhase = PRE_SALE; // total coins minted so far mintedCoins = 0; // total funds raised totalReceived = 0; saleClosed = true; } /** * Fallback function to be invoked when a value is sent without a function call. */ function() public payable { // Make sure the sale is active require(!saleClosed); // Minimum amount is 0.02 eth require(msg.value >= 0.02 ether); // If 1500 eth is received switch the sale price if (totalReceived >= 1500 ether) { currentSalePhase = SALE; } uint256 c = mul(msg.value, currentSalePhase); // Calculate tokens to mint based on the "current sale phase" uint256 amount = c; // Make sure that mintedCoins don't exceed the hardcap sale require(mintedCoins + amount <= hardCapSale); // Check for totalSupply max amount balances[msg.sender] += amount; // Increase the number of minted coins mintedCoins += amount; //Increase totalSupply by amount totalSupply += amount; // Track of total value received totalReceived += msg.value; Transfer(this, msg.sender, amount); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * Get Tokens for the company */ function getCompanyToken(uint256 amount) public onlyDirector returns (bool success) { amount = amount * 10 ** uint256(decimals); require((totalSupply + amount) <= tokenCap); balances[director] = amount; totalSupply += amount; return true; } /** * Lock the crowdsale */ function closeSale() public onlyDirector returns (bool success) { saleClosed = true; return true; } /** * Unlock the crowd sale. */ function openSale() public onlyDirector returns (bool success) { saleClosed = false; return true; } /** * Set the price to pre-sale */ function setPriceToPreSale() public onlyDirector returns (bool success) { currentSalePhase = PRE_SALE; return true; } /** * Set the price to reg sale. */ function setPriceToRegSale() public onlyDirector returns (bool success) { currentSalePhase = SALE; return true; } /** * Withdraw funds from the contract */ function withdrawFunds() public { director.transfer(this.balance); } /** * Transfers the director to a new address */ function transferDirector(address newDirector) public onlyDirector { director = newDirector; } /** * Returns total */ function totalSupply() public view returns (uint256) { return totalSupply; } /** * Balance of a particular account */ function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool success) { // Make sure the sender has enough value in their account require(balances[msg.sender] >= _value && _value > 0); // Subtract value from sender's account balances[msg.sender] = balances[msg.sender] - _value; // Add value to receiver's account balances[_to] = add(balances[_to], _value); // Log Transfer(msg.sender, _to, _value); return true; } /** * Allow spender to spend the value amount on your behalf. * If this function is called again it overwrites the current allowance with _value. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * Spend value from a different account granted you have allowance to use the value amount. * If this function is called again it overwrites the current allowance with _value. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0); balances[_from] = balances[_from] - _value; balances[_to] = add(balances[_to], _value); allowed[_from][msg.sender] = sub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } /** * Returns the amount which _spender is still allowed to withdraw from _owner */ function allowance(address _owner, address _spender) public constant returns (uint256) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
Allow spender to spend the value amount on your behalf. If this function is called again it overwrites the current allowance with _value./
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
12,591,425
pragma solidity 0.4.24; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using &#39;super&#39; where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public 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 DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit 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 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/DynamicRateCrowdsale.sol contract DynamicRateCrowdsale is Crowdsale { using SafeMath for uint256; // 奖励汇率 uint256 public bonusRate; constructor(uint256 _bonusRate) public { require(_bonusRate > 0); bonusRate = _bonusRate; } function getCurrentRate() public view returns (uint256) { return rate.add(bonusRate); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return currentRate.mul(_weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol /** * @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; address public 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)); tokenWallet = _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 token.allowance(tokenWallet, 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.transferFrom(tokenWallet, _beneficiary, _tokenAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/EoptCrowdsale.sol contract EoptCrowdsale is Crowdsale, CappedCrowdsale, AllowanceCrowdsale, DynamicRateCrowdsale, TimedCrowdsale, Ownable { constructor( uint256 _rate, uint256 _bonusRate, address _wallet, ERC20 _token, uint256 _cap, address _tokenWallet, uint256 _openingTime, uint256 _closingTime ) Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) AllowanceCrowdsale(_tokenWallet) TimedCrowdsale(_openingTime, _closingTime) DynamicRateCrowdsale(_bonusRate) public { } // 购买事件 event Purchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 weiRaised, uint256 rate, uint256 bonusRate, uint256 cap ); function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { super._updatePurchasingState(_beneficiary, _weiAmount); uint256 tokens = _getTokenAmount(_weiAmount); emit Purchase( msg.sender, _beneficiary, _weiAmount, tokens, weiRaised, rate, bonusRate, cap ); } // 设置汇率,1 ETH : N TOKEN function setRate(uint256 _rate) onlyOwner public { require(_rate > 0 && _rate < 1000000); rate = _rate; } // 设置奖励汇率,1 ETH : N TOKEN(bonus) function setBonusRate(uint256 _bonusRate) onlyOwner public { require(_bonusRate > 0 && _bonusRate < 1000000); bonusRate = _bonusRate; } // 设置众筹结束时间 function setClosingTime(uint256 _closingTime) onlyOwner public { require(_closingTime >= block.timestamp); require(_closingTime >= openingTime); closingTime = _closingTime; } // 设置众筹总量限额 0 < _cap < 50w ETH function setCap(uint256 _cap) onlyOwner public { require(_cap > 0 && _cap < 500000000000000000000000); cap = _cap; } // 设置EOPT的代币合约地址 function setToken(ERC20 _token) onlyOwner public { require(_token != address(0)); token = _token; } // 设置提供EOPT的钱包地址 function setTokenWallet(address _tokenWallet) onlyOwner public { require(_tokenWallet != address(0)); tokenWallet = _tokenWallet; } // 设置接收众筹ETH的钱包地址 function setWallet(address _wallet) onlyOwner public { require(_wallet != address(0)); wallet = _wallet; } }
设置众筹总量限额 0 < _cap < 50w ETH
function setCap(uint256 _cap) onlyOwner public { require(_cap > 0 && _cap < 500000000000000000000000); cap = _cap; }
10,667,684
//// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 < 0.9.0; pragma abicoder v2; import './professional.sol'; /** * Factory contract for deploying new patient database and controller contracts */ contract PatientFactory { struct PatientAddrs { address database; address controller; } mapping(string => PatientAddrs) private created_patients; function create_patient(string memory name_in, string memory birthday_in, string memory gender_in, string memory email_in) public { PatientController pc = new PatientController(); address new_controller = address(pc); address new_patient_db = address(new PatientDatabase(name_in, birthday_in, gender_in, email_in, new_controller)); pc.bind(new_patient_db); created_patients[email_in] = PatientAddrs({ database: new_patient_db, controller: new_controller }); } function get_created_patient(string memory email_in) public view returns(address, address) { return (created_patients[email_in].database, created_patients[email_in].controller); } } /** * Stores patient information and access tokens for patients' files */ contract PatientDatabase { // basic infos string private name; string private birthday; string private gender; string private email; // the patient controller that manages interaction with this contract address private controller; // data storage mapping(string => string) private tokens; string[] private filenames; // data structures to manage accessibility of patient's data mapping(address => bool) private has_access; mapping(string => address) private authorized_email_to_addr; string[] private authorized_professionals; // data structures for users to handle access requests mapping(string => address) private requests_received; string[] private unprocessed_requests; // professional information struct struct ProfessionalInfo { string name; string gender; string email; string institution; } modifier file_exists(string memory filename) { require(bytes(tokens[filename]).length != 0); _; } modifier file_not_exists(string memory filename) { require(bytes(tokens[filename]).length == 0); _; } modifier owner_restricted() { require(msg.sender == controller); _; } modifier authorized_restricted() { require(has_access[msg.sender]); _; } constructor(string memory name_in, string memory birthday_in, string memory gender_in, string memory email_in, address controller_in) { name = name_in; birthday = birthday_in; gender = gender_in; email = email_in; controller = controller_in; has_access[controller_in] = true; } // getters for storage variables function get_name() public authorized_restricted view returns (string memory) { return name; } function get_birthday() public authorized_restricted view returns (string memory) { return birthday; } function get_gender() public authorized_restricted view returns (string memory) { return gender; } function get_email() public authorized_restricted view returns (string memory) { return email; } // functions related to file management function add_file(string memory filename, string memory token) external file_not_exists(filename) owner_restricted { filenames.push(filename); tokens[filename] = token; } function view_file(string memory filename) external view file_exists(filename) authorized_restricted returns(string memory) { return tokens[filename]; } function delete_file(string memory filename) external file_exists(filename) owner_restricted { tokens[filename] = ""; for (uint256 i=0; i < filenames.length; i++) { if (keccak256(abi.encodePacked((filenames[i]))) == keccak256(abi.encodePacked((filename)))) { filenames[i] = filenames[filenames.length - 1]; break; } } filenames.pop(); } function change_filename(string memory old_filename, string memory new_filename) external file_exists(old_filename) file_not_exists(new_filename) owner_restricted { tokens[new_filename] = tokens[old_filename]; tokens[old_filename] = ""; for (uint256 i=0; i < filenames.length; i++) { if (keccak256(abi.encodePacked((filenames[i]))) == keccak256(abi.encodePacked((old_filename)))) { filenames[i] = new_filename; } } } function get_filenames() external view authorized_restricted returns (string[] memory) { return filenames; } // functions related to accessibility management function send_view_request(address professional_addr, string memory professional_email) external { require(!has_access[professional_addr]); require(requests_received[professional_email] == address(0)); unprocessed_requests.push(professional_email); requests_received[professional_email] = professional_addr; } function process_request(string memory professional_email, bool approve) external owner_restricted { address professional_addr = requests_received[professional_email]; require(professional_addr != address(0)); has_access[professional_addr] = approve; if (approve) { authorized_professionals.push(professional_email); authorized_email_to_addr[professional_email] = professional_addr; } ProfessionalController(requests_received[professional_email]).process_request(email, address(this), approve); // remove from unprocessed_requests array for (uint256 i=0; i < unprocessed_requests.length; i++) { if (keccak256(abi.encodePacked((unprocessed_requests[i]))) == keccak256(abi.encodePacked((professional_email)))) { unprocessed_requests[i] = unprocessed_requests[unprocessed_requests.length - 1]; break; } } unprocessed_requests.pop(); requests_received[professional_email] = address(0); } function ban_professional(string memory professional_email) external owner_restricted { require(has_access[authorized_email_to_addr[professional_email]]); ProfessionalController(authorized_email_to_addr[professional_email]).delete_patient(email); has_access[authorized_email_to_addr[professional_email]] = false; authorized_email_to_addr[professional_email] = address(0); for (uint256 i=0; i < authorized_professionals.length; i++) { if (keccak256(abi.encodePacked((authorized_professionals[i]))) == keccak256(abi.encodePacked((professional_email)))) { authorized_professionals[i] = authorized_professionals[authorized_professionals.length - 1]; break; } } authorized_professionals.pop(); } function get_unprocessed_requests() external owner_restricted view returns(ProfessionalInfo[] memory) { ProfessionalInfo[] memory professional_requests = new ProfessionalInfo[](unprocessed_requests.length); for (uint256 i = 0; i < unprocessed_requests.length; i++) { ProfessionalController p = ProfessionalController(requests_received[unprocessed_requests[i]]); ProfessionalInfo memory p_info = ProfessionalInfo({ name: p.get_name(), gender: p.get_gender(), email: p.get_email(), institution: p.get_institution() }); professional_requests[i] = p_info; } return professional_requests; } function get_authorized_professionals() external owner_restricted view returns(ProfessionalInfo[] memory){ ProfessionalInfo[] memory authorized = new ProfessionalInfo[](authorized_professionals.length); for (uint256 i = 0; i < authorized_professionals.length; i++) { ProfessionalController p = ProfessionalController(authorized_email_to_addr[authorized_professionals[i]]); ProfessionalInfo memory p_info = ProfessionalInfo({ name: p.get_name(), gender: p.get_gender(), email: p.get_email(), institution: p.get_institution() }); authorized[i] = p_info; } return authorized; } } /** * Contract for interaction with patients' database. * Adds a layer of indirection to control accessibility associated with ethereum address thus ensuring security */ contract PatientController { // ensures the controller only binds with the database contract at deploy time by the factory contract bool private binded; // the database contract for this specific patient PatientDatabase private database; constructor() { binded = false; } function bind(address patient_db_addr) external { require(!binded); database = PatientDatabase(patient_db_addr); binded = true; } function add_file(string memory filename, string memory token) external { database.add_file(filename, token); } function view_file(string memory filename) external view returns(string memory) { return database.view_file(filename); } function delete_file(string memory filename) external { database.delete_file(filename); } function change_filename(string memory old_filename, string memory new_filename) external { database.change_filename(old_filename, new_filename); } function get_filenames() external view returns (string[] memory) { return database.get_filenames(); } function process_request(string memory professional_email, bool approve) external { database.process_request(professional_email, approve); } function ban_professional(string memory professional_email) external { database.ban_professional(professional_email); } function get_unprocessed_requests() external view returns(PatientDatabase.ProfessionalInfo[] memory) { return database.get_unprocessed_requests(); } function get_authorized_professionals() external view returns(PatientDatabase.ProfessionalInfo[] memory) { return database.get_authorized_professionals(); } function get_name() public view returns (string memory) { return database.get_name(); } function get_birthday() public view returns (string memory) { return database.get_birthday(); } function get_gender() public view returns (string memory) { return database.get_gender(); } function get_email() public view returns (string memory) { return database.get_email(); } }
functions related to accessibility management
function send_view_request(address professional_addr, string memory professional_email) external { require(!has_access[professional_addr]); require(requests_received[professional_email] == address(0)); unprocessed_requests.push(professional_email); requests_received[professional_email] = professional_addr; }
12,784,886
/** *Submitted for verification at Etherscan.io on 2021-07-28 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IAaveDistributionManager interface IAaveDistributionManager { event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated( address indexed user, address indexed asset, uint256 index ); event DistributionEndUpdated(uint256 newDistributionEnd); /** * @dev Sets the end date for the distribution * @param distributionEnd The end date timestamp **/ function setDistributionEnd(uint256 distributionEnd) external; /** * @dev Gets the end date for the distribution * @return The end of the distribution **/ function getDistributionEnd() external view returns (uint256); /** * @dev for backwards compatibility with the previous DistributionManager used * @return The end of the distribution **/ function DISTRIBUTION_END() external view returns (uint256); /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) external view returns (uint256); /** * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); } // Part: ILendingPoolAddressesProvider /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // Part: IPriceOracle interface IPriceOracle { function getAssetPrice(address _asset) external view returns (uint256); } // Part: IStakedAave interface IStakedAave { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; } // Part: IUniswapV3SwapCallback /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: IAaveIncentivesController interface IAaveIncentivesController is IAaveDistributionManager { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed( address indexed user, address indexed to, address indexed claimer, uint256 amount ); event ClaimerSet(address indexed user, address indexed claimer); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets( address[] calldata assets, uint256[] calldata emissionsPerSecond ) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); } // Part: ILendingPool interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw( address indexed reserve, address indexed user, address indexed to, uint256 amount ); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled( address indexed reserve, address indexed user ); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled( address indexed reserve, address indexed user ); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate( address indexed reserve, address indexed user ); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount 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 **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress( address reserve, address rateStrategyAddress ) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // Part: ISwapRouter /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // Part: OpenZeppelin/[email protected]/ERC20 /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @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.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: Strategy.sol contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; ILendingPoolAddressesProvider public constant ADDRESS_PROVIDER = ILendingPoolAddressesProvider( 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5 ); IERC20 public immutable aToken; IERC20 public immutable vToken; ILendingPool public immutable LENDING_POOL; uint256 public immutable DECIMALS; // For toETH conversion // stkAAVE IERC20 public constant reward = IERC20(0x4da27a545c0c5B758a6BA100e3a049001de870f5); // Token we farm and swap to want / aToken // Hardhcoded from the Liquidity Mining docs: https://docs.aave.com/developers/guides/liquidity-mining IAaveIncentivesController public constant INCENTIVES_CONTROLLER = IAaveIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5); // For Swapping ISwapRouter public constant ROUTER = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); IERC20 public constant AAVE_TOKEN = IERC20(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); IERC20 public constant WETH_TOKEN = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // Min Price we tollerate when swapping from stkAAVE to AAVE uint256 public minStkAAVEPRice = 9500; // 95% uint256 public minAAVEToWantPrice = 8000; // 80% // Seems like Oracle is slightly off // Should we harvest before prepareMigration bool public harvestBeforeMigrate = true; // Should we ensure the swap will be within slippage params before performing it during normal harvest? bool public checkSlippageOnHarvest = true; // Leverage uint256 public constant MAX_BPS = 10000; uint256 public minHealth = 1080000000000000000; // 1.08 with 18 decimals this is slighly above 70% tvl uint256 public minRebalanceAmount = 50000000; // 0.5 should be changed based on decimals (btc has 8) constructor(address _vault) public BaseStrategy(_vault) { // You can set these parameters on deployment to whatever you want maxReportDelay = 6300; profitFactor = 100; debtThreshold = 0; // Get lending Pool ILendingPool lendingPool = ILendingPool(ADDRESS_PROVIDER.getLendingPool()); // Set lending pool as immutable LENDING_POOL = lendingPool; // Get Tokens Addresses DataTypes.ReserveData memory data = lendingPool.getReserveData(address(want)); // Get aToken aToken = IERC20(data.aTokenAddress); // Get vToken vToken = IERC20(data.variableDebtTokenAddress); // Get Decimals DECIMALS = ERC20(address(want)).decimals(); want.safeApprove(address(lendingPool), type(uint256).max); reward.safeApprove(address(ROUTER), type(uint256).max); AAVE_TOKEN.safeApprove(address(ROUTER), type(uint256).max); } function setMinHealth(uint256 newMinHealth) external onlyKeepers { require(newMinHealth >= 1000000000000000000, "Need higher health"); minHealth = newMinHealth; } function setHarvestBeforeMigrate(bool newHarvestBeforeMigrate) external onlyKeepers { harvestBeforeMigrate = newHarvestBeforeMigrate; } function setCheckSlippageOnHarvest(bool newCheckSlippageOnHarvest) external onlyKeepers { checkSlippageOnHarvest = newCheckSlippageOnHarvest; } function setMinStkAAVEPRice(uint256 newMinStkAAVEPRice) external onlyKeepers { require(newMinStkAAVEPRice >= 0 && newMinStkAAVEPRice <= MAX_BPS); minStkAAVEPRice = newMinStkAAVEPRice; } function setMinPrice(uint256 newMinAAVEToWantPrice) external onlyKeepers { require(newMinAAVEToWantPrice >= 0 && newMinAAVEToWantPrice <= MAX_BPS); minAAVEToWantPrice = newMinAAVEToWantPrice; } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { // Add your own name here, suggestion e.g. "StrategyCreamYFI" return "Strategy-Levered-AAVE-wBTC"; } function estimatedTotalAssets() public view override returns (uint256) { // Balance of want + balance in AAVE uint256 liquidBalance = want.balanceOf(address(this)).add(deposited()).sub(borrowed()); // Return balance + reward return liquidBalance.add(valueOfRewards()); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // NOTE: This means that if we are paying back we just deleverage // While if we are not paying back, we are harvesting rewards if (_debtOutstanding > 0) { // Withdraw and Repay uint256 toWithdraw = _debtOutstanding; // Get it all out _divestFromAAVE(); // Get rewards _claimRewardsAndGetMoreWant(); // Repay debt uint256 maxRepay = want.balanceOf(address(this)); if (_debtOutstanding > maxRepay) { // we can't pay all, means we lost some _loss = _debtOutstanding.sub(maxRepay); _debtPayment = maxRepay; } else { // We can pay all, let's do it _debtPayment = toWithdraw; } } else { // Do normal Harvest _debtPayment = 0; // Get current amount of want // used to estimate profit uint256 beforeBalance = want.balanceOf(address(this)); // Claim stkAAVE -> swap into want _claimRewardsAndGetMoreWant(); (uint256 earned, uint256 lost) = _repayAAVEBorrow(beforeBalance); _profit = earned; _loss = lost; } } function _repayAAVEBorrow(uint256 beforeBalance) internal returns (uint256 _profit, uint256 _loss) { uint256 afterSwapBalance = want.balanceOf(address(this)); uint256 wantFromSwap = afterSwapBalance.sub(beforeBalance); // Calculate Gain from AAVE interest // NOTE: This should never happen as we take more debt than we earn uint256 currentWantInAave = deposited().sub(borrowed()); uint256 initialDeposit = vault.strategies(address(this)).totalDebt; if (currentWantInAave > initialDeposit) { uint256 interestProfit = currentWantInAave.sub(initialDeposit); LENDING_POOL.withdraw(address(want), interestProfit, address(this)); // Withdraw interest of aToken so that now we have exactly the same amount } uint256 afterBalance = want.balanceOf(address(this)); uint256 wantEarned = afterBalance.sub(beforeBalance); // Earned before repaying debt // Pay off any debt // Debt is equal to negative of canBorrow uint256 toRepay = debtBelowHealth(); if (toRepay > wantEarned) { // We lost some money // Repay all we can, rest is loss LENDING_POOL.repay(address(want), wantEarned, 2, address(this)); _loss = toRepay.sub(wantEarned); // Notice that once the strats starts loosing funds here, you should probably retire it as it's not profitable } else { // We made money or are even // Let's repay the debtBelowHealth uint256 repaid = toRepay; _profit = wantEarned.sub(repaid); if (repaid > 0) { LENDING_POOL.repay(address(want), repaid, 2, address(this)); } } } function adjustPosition(uint256 _debtOutstanding) internal override { // TODO: Do something to invest excess `want` tokens (from the Vault) into your positions // NOTE: Try to adjust positions so that `_debtOutstanding` can be freed up on *next* harvest (not immediately) uint256 wantAvailable = want.balanceOf(address(this)); if (wantAvailable > _debtOutstanding) { uint256 toDeposit = wantAvailable.sub(_debtOutstanding); LENDING_POOL.deposit(address(want), toDeposit, address(this), 0); // Lever up _invest(); } } function balanceOfRewards() public view returns (uint256) { // Get rewards address[] memory assets = new address[](2); assets[0] = address(aToken); assets[1] = address(vToken); uint256 totalRewards = INCENTIVES_CONTROLLER.getRewardsBalance(assets, address(this)); return totalRewards; } function valueOfAAVEToWant(uint256 aaveAmount) public view returns (uint256) { return ethToWant(AAVEToETH(aaveAmount)); } function valueOfRewards() public view returns (uint256) { return valueOfAAVEToWant(balanceOfRewards()); } // Get stkAAVE function _claimRewards() internal { // Get rewards address[] memory assets = new address[](2); assets[0] = address(aToken); assets[1] = address(vToken); // Get Rewards, withdraw all INCENTIVES_CONTROLLER.claimRewards( assets, type(uint256).max, address(this) ); } function _fromSTKAAVEToAAVE(uint256 rewardsAmount, uint256 minOut) internal { // Swap Rewards in UNIV3 // NOTE: Unoptimized, can be frontrun and most importantly this pool is low liquidity ISwapRouter.ExactInputSingleParams memory fromRewardToAAVEParams = ISwapRouter.ExactInputSingleParams( address(reward), address(AAVE_TOKEN), 10000, address(this), now, rewardsAmount, // wei minOut, 0 ); ROUTER.exactInputSingle(fromRewardToAAVEParams); } function _fromAAVEToWant(uint256 amountIn, uint256 minOut) internal { // We now have AAVE tokens, let's get want bytes memory path = abi.encodePacked( address(AAVE_TOKEN), uint24(10000), address(WETH_TOKEN), uint24(10000), address(want) ); ISwapRouter.ExactInputParams memory fromAAVETowBTCParams = ISwapRouter.ExactInputParams( path, address(this), now, amountIn, minOut ); ROUTER.exactInput(fromAAVETowBTCParams); } function _claimRewardsAndGetMoreWant() internal { _claimRewards(); uint256 rewardsAmount = reward.balanceOf(address(this)); if (rewardsAmount == 0) { return; } // Specify a min out uint256 minAAVEOut = rewardsAmount.mul(minStkAAVEPRice).div(MAX_BPS); _fromSTKAAVEToAAVE(rewardsAmount, minAAVEOut); uint256 aaveToSwap = AAVE_TOKEN.balanceOf(address(this)); uint256 minWantOut = 0; if (checkSlippageOnHarvest) { minWantOut = valueOfAAVEToWant(aaveToSwap) .mul(minAAVEToWantPrice) .div(MAX_BPS); } _fromAAVEToWant(aaveToSwap, minWantOut); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // TODO: Do stuff here to free up to `_amountNeeded` from all positions back into `want` // NOTE: Maintain invariant `want.balanceOf(this) >= _liquidatedAmount` // NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded` // Lever Down _divestFromAAVE(); uint256 totalAssets = want.balanceOf(address(this)); if (_amountNeeded > totalAssets) { _liquidatedAmount = totalAssets; _loss = _amountNeeded.sub(totalAssets); } else { _liquidatedAmount = _amountNeeded; } } // Withdraw all from AAVE Pool function liquidateAllPositions() internal override returns (uint256) { // Repay all debt and divest _divestFromAAVE(); // Get rewards before leaving _claimRewardsAndGetMoreWant(); // Return amount freed return want.balanceOf(address(this)); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // TODO: Transfer any non-`want` tokens to the new strategy // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one // This is gone if we use upgradeable //Divest all _divestFromAAVE(); if (harvestBeforeMigrate) { // Harvest rewards one last time _claimRewardsAndGetMoreWant(); } // Just in case we don't fully liquidate to want if (aToken.balanceOf(address(this)) > 0) { aToken.safeTransfer(_newStrategy, aToken.balanceOf(address(this))); } if (reward.balanceOf(address(this)) > 0) { reward.safeTransfer(_newStrategy, reward.balanceOf(address(this))); } } // Override this to add all tokens/tokenized positions this contract manages // on a *persistent* basis (e.g. not just for swapping back to want ephemerally) // NOTE: Do *not* include `want`, already included in `sweep` below // // Example: // // function protectedTokens() internal override view returns (address[] memory) { // address[] memory protected = new address[](3); // protected[0] = tokenA; // protected[1] = tokenB; // protected[2] = tokenC; // return protected; // } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = address(aToken); protected[1] = address(reward); return protected; } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { address priceOracle = ADDRESS_PROVIDER.getPriceOracle(); uint256 priceInEth = IPriceOracle(priceOracle).getAssetPrice(address(want)); // Opposite of priceInEth // Multiply first to keep rounding uint256 priceInWant = _amtInWei.mul(10**DECIMALS).div(priceInEth); return priceInWant; } function AAVEToETH(uint256 _amt) public view returns (uint256) { address priceOracle = ADDRESS_PROVIDER.getPriceOracle(); uint256 priceInEth = IPriceOracle(priceOracle).getAssetPrice(address(AAVE_TOKEN)); // Price in ETH // AMT * Price in ETH / Decimals uint256 aaveToEth = _amt.mul(priceInEth).div(10**18); return aaveToEth; } /* Leverage functions */ function deposited() public view returns (uint256) { return aToken.balanceOf(address(this)); } function borrowed() public view returns (uint256) { return vToken.balanceOf(address(this)); } // What should we repay? function debtBelowHealth() public view returns (uint256) { ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) = LENDING_POOL.getUserAccountData(address(this)); // How much did we go off of minHealth? //NOTE: We always borrow as much as we can uint256 maxBorrow = deposited().mul(ltv).div(MAX_BPS); if (healthFactor < minHealth && borrowed() > maxBorrow) { uint256 maxValue = borrowed().sub(maxBorrow); return maxValue; } return 0; } // NOTE: We always borrow max, no fucks given function canBorrow() public view returns (uint256) { ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) = LENDING_POOL.getUserAccountData(address(this)); if (healthFactor > minHealth) { // Amount = deposited * ltv - borrowed // Div MAX_BPS because because ltv / maxbps is the percent uint256 maxValue = deposited().mul(ltv).div(MAX_BPS).sub(borrowed()); // Don't borrow if it's dust, save gas if (maxValue < minRebalanceAmount) { return 0; } return maxValue; } return 0; } function _invest() internal { // Loop on it until it's properly done uint256 max_iterations = 5; for (uint256 i = 0; i < max_iterations; i++) { uint256 toBorrow = canBorrow(); if (toBorrow > 0) { LENDING_POOL.borrow( address(want), toBorrow, 2, 0, address(this) ); LENDING_POOL.deposit(address(want), toBorrow, address(this), 0); } else { break; } } } // Divest all from AAVE, awful gas, but hey, it works function _divestFromAAVE() internal { uint256 repayAmount = canRepay(); // The "unsafe" (below target health) you can withdraw // Loop to withdraw until you have the amount you need while (repayAmount != uint256(-1)) { _withdrawStepFromAAVE(repayAmount); repayAmount = canRepay(); } if (deposited() > 0) { // Withdraw the rest here LENDING_POOL.withdraw( address(want), type(uint256).max, address(this) ); } } // Withdraw and Repay AAVE Debt function _withdrawStepFromAAVE(uint256 canRepay) internal { if (canRepay > 0) { //Repay this step LENDING_POOL.withdraw(address(want), canRepay, address(this)); LENDING_POOL.repay(address(want), canRepay, 2, address(this)); } } // returns 95% of the collateral we can withdraw from aave, used to loop and repay debts function canRepay() public view returns (uint256) { ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) = LENDING_POOL.getUserAccountData(address(this)); uint256 aBalance = deposited(); uint256 vBalance = borrowed(); if (vBalance == 0) { return uint256(-1); //You have repaid all } uint256 diff = aBalance.sub(vBalance.mul(10000).div(currentLiquidationThreshold)); uint256 inWant = diff.mul(95).div(100); // Take 95% just to be safe return inWant; } /** Manual Functions */ /** Leverage Manual Functions */ // Emergency function to immediately deleverage to 0 function manualDivestFromAAVE() public onlyVaultManagers { _divestFromAAVE(); } // Manually perform 5 loops to lever up // Safe because it's capped by canBorrow function manualLeverUp() public onlyVaultManagers { _invest(); } // Emergency function that we can use to deleverage manually if something is broken // If something goes wrong, just try smaller and smaller can repay amounts function manualWithdrawStepFromAAVE(uint256 toRepay) public onlyVaultManagers { _withdrawStepFromAAVE(toRepay); } // Take some funds from manager and use them to repay // Useful if you ever go below 1 HF and somehow you didn't get liquidated function manualRepayFromManager(uint256 toRepay) public onlyVaultManagers { want.safeTransferFrom(msg.sender, address(this), toRepay); LENDING_POOL.repay(address(want), toRepay, 2, address(this)); } /** DCA Manual Functions */ // Get the rewards function manualClaimRewards() public onlyVaultManagers { _claimRewards(); } // Initiate 10 days cooldown period manually // You can use this if you believe V3 Pool is too illiquid function manualCooldownRewards() public onlyVaultManagers { IStakedAave stkAAVE = IStakedAave(address(reward)); stkAAVE.claimRewards(address(this), type(uint256).max); stkAAVE.cooldown(); } // Manually redeem rewards, claiming AAVE // You can use this if you believe V3 Pool is too illiquid function manualRedeemRewards() public onlyVaultManagers { IStakedAave stkAAVE = IStakedAave(address(reward)); stkAAVE.claimRewards(address(this), type(uint256).max); stkAAVE.redeem(address(this), type(uint256).max); } // Swap from stkAAVE to AAVE ///@param amountToSwap Amount of stkAAVE to Swap, NOTE: You have to calculate the amount!! ///@param multiplierInWei pricePerToken including slippage, will be divided by 10 ** 18 function manualSwapFromStkAAVEToAAVE( uint256 amountToSwap, uint256 multiplierInWei ) public onlyVaultManagers { uint256 amountOutMinimum = amountToSwap.mul(multiplierInWei).div(10**18); _fromSTKAAVEToAAVE(amountToSwap, amountOutMinimum); } // Swap from AAVE to Want ///@param amountToSwap Amount of AAVE to Swap, NOTE: You have to calculate the amount!! ///@param multiplierInWei pricePerToken including slippage, will be divided by 10 ** 18 function manualSwapFromAAVEToWant( uint256 amountToSwap, uint256 multiplierInWei ) public onlyVaultManagers { uint256 amountOutMinimum = amountToSwap.mul(multiplierInWei).div(10**18); _fromAAVEToWant(amountToSwap, amountOutMinimum); } }
Withdraw all from AAVE Pool Repay all debt and divest Get rewards before leaving Return amount freed
function liquidateAllPositions() internal override returns (uint256) { _divestFromAAVE(); _claimRewardsAndGetMoreWant(); return want.balanceOf(address(this)); }
6,544,848
./full_match/43113/0x7fCe6BC41befcdb73f3E7562f6F648AB6C0C1B6c/sources/SDACs/FileBasedSDAC.sol
file based write permission. Assumes the data vault has validated the requester's ID
function canWrite( address requester, address file ) public view returns (bool) { return (getPermissions(requester, file) & WRITE_BIT) > 0; }
13,151,665
./partial_match/1/0x4B2c41dD64c43EdaCf741EE0b9B549e3E00B3D3a/sources/StarNFTV3.sol
See {IERC721-transferFrom}./
function transferFrom( address from, address to, uint256 tokenId ) public override { require(transferable, "disabled"); require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not approved or owner" ); _transfer(from, to, tokenId); }
9,397,557
// SPDX-License-Identifier: GPL-3.0-only pragma solidity =0.7.6; pragma abicoder v2; // interface import {IController} from "../interfaces/IController.sol"; import {IWPowerPerp} from "../interfaces/IWPowerPerp.sol"; import {IOracle} from "../interfaces/IOracle.sol"; import {IWETH9} from "../interfaces/IWETH9.sol"; import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {IController} from "../interfaces/IController.sol"; // contract import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {StrategyBase} from "./base/StrategyBase.sol"; import {StrategyFlashSwap} from "./base/StrategyFlashSwap.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; // lib import {Address} from "@openzeppelin/contracts/utils/Address.sol"; // StrategyMath licensed under AGPL-3.0-only import {StrategyMath} from "./base/StrategyMath.sol"; import {Power2Base} from "../libs/Power2Base.sol"; /** * @dev CrabStrategy contract * @notice Contract for Crab strategy * @author Opyn team */ contract CrabStrategy is StrategyBase, StrategyFlashSwap, ReentrancyGuard, Ownable { using StrategyMath for uint256; using Address for address payable; /// @dev the cap in ETH for the strategy, above which deposits will be rejected uint256 public strategyCap; /// @dev the TWAP_PERIOD used in the PowerPerp Controller contract uint32 public constant POWER_PERP_PERIOD = 420 seconds; /// @dev twap period to use for hedge calculations uint32 public hedgingTwapPeriod = 420 seconds; /// @dev enum to differentiate between uniswap swap callback function source enum FLASH_SOURCE { FLASH_DEPOSIT, FLASH_WITHDRAW, FLASH_HEDGE_SELL, FLASH_HEDGE_BUY } /// @dev ETH:WSqueeth uniswap pool address public immutable ethWSqueethPool; /// @dev strategy uniswap oracle address public immutable oracle; address public immutable ethQuoteCurrencyPool; address public immutable quoteCurrency; /// @dev strategy will only allow hedging if collateral to trade is at least a set percentage of the total strategy collateral uint256 public deltaHedgeThreshold = 1e15; /// @dev time difference to trigger a hedge (seconds) uint256 public hedgeTimeThreshold; /// @dev price movement to trigger a hedge (0.1*1e18 = 10%) uint256 public hedgePriceThreshold; /// @dev hedge auction duration (seconds) uint256 public auctionTime; /// @dev start auction price multiplier for hedge buy auction and reserve price for hedge sell auction (scaled 1e18) uint256 public minPriceMultiplier; /// @dev start auction price multiplier for hedge sell auction and reserve price for hedge buy auction (scaled 1e18) uint256 public maxPriceMultiplier; /// @dev timestamp when last hedge executed uint256 public timeAtLastHedge; /// @dev WSqueeth/Eth price when last hedge executed uint256 public priceAtLastHedge; /// @dev set to true when redeemShortShutdown has been called bool private hasRedeemedInShutdown; struct FlashDepositData { uint256 totalDeposit; } struct FlashWithdrawData { uint256 crabAmount; } struct FlashHedgeData { uint256 wSqueethAmount; uint256 ethProceeds; uint256 minWSqueeth; uint256 minEth; } event Deposit(address indexed depositor, uint256 wSqueethAmount, uint256 lpAmount); event Withdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount, uint256 ethWithdrawn); event WithdrawShutdown(address indexed withdrawer, uint256 crabAmount, uint256 ethWithdrawn); event FlashDeposit(address indexed depositor, uint256 depositedAmount, uint256 tradedAmountOut); event FlashWithdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount); event FlashDepositCallback(address indexed depositor, uint256 flashswapDebt, uint256 excess); event FlashWithdrawCallback(address indexed withdrawer, uint256 flashswapDebt, uint256 excess); event TimeHedgeOnUniswap( address indexed hedger, uint256 hedgeTimestamp, uint256 auctionTriggerTimestamp, uint256 minWSqueeth, uint256 minEth ); event PriceHedgeOnUniswap( address indexed hedger, uint256 hedgeTimestamp, uint256 auctionTriggerTimestamp, uint256 minWSqueeth, uint256 minEth ); event TimeHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp); event PriceHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp); event Hedge( address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionPrice, uint256 wSqueethHedgeTargetAmount, uint256 ethHedgetargetAmount ); event HedgeOnUniswap( address indexed hedger, bool auctionType, uint256 auctionPrice, uint256 wSqueethHedgeTargetAmount, uint256 ethHedgetargetAmount ); event ExecuteSellAuction(address indexed buyer, uint256 wSqueethSold, uint256 ethBought, bool isHedgingOnUniswap); event ExecuteBuyAuction(address indexed seller, uint256 wSqueethBought, uint256 ethSold, bool isHedgingOnUniswap); event SetStrategyCap(uint256 newCapAmount); event SetDeltaHedgeThreshold(uint256 newDeltaHedgeThreshold); event SetHedgingTwapPeriod(uint32 newHedgingTwapPeriod); event SetHedgeTimeThreshold(uint256 newHedgeTimeThreshold); event SetHedgePriceThreshold(uint256 newHedgePriceThreshold); event SetAuctionTime(uint256 newAuctionTime); event SetMinPriceMultiplier(uint256 newMinPriceMultiplier); event SetMaxPriceMultiplier(uint256 newMaxPriceMultiplier); /** * @notice strategy constructor * @dev this will open a vault in the power token contract and store the vault ID * @param _wSqueethController power token controller address * @param _oracle oracle address * @param _weth weth address * @param _uniswapFactory uniswap factory address * @param _ethWSqueethPool eth:wSqueeth uniswap pool address * @param _hedgeTimeThreshold hedge time threshold (seconds) * @param _hedgePriceThreshold hedge price threshold (0.1*1e18 = 10%) * @param _auctionTime auction duration (seconds) * @param _minPriceMultiplier minimum auction price multiplier (0.9*1e18 = min auction price is 90% of twap) * @param _maxPriceMultiplier maximum auction price multiplier (1.1*1e18 = max auction price is 110% of twap) */ constructor( address _wSqueethController, address _oracle, address _weth, address _uniswapFactory, address _ethWSqueethPool, uint256 _hedgeTimeThreshold, uint256 _hedgePriceThreshold, uint256 _auctionTime, uint256 _minPriceMultiplier, uint256 _maxPriceMultiplier ) StrategyBase(_wSqueethController, _weth, "Crab Strategy", "Crab") StrategyFlashSwap(_uniswapFactory) { require(_oracle != address(0), "invalid oracle address"); require(_ethWSqueethPool != address(0), "invalid ETH:WSqueeth address"); require(_hedgeTimeThreshold > 0, "invalid hedge time threshold"); require(_hedgePriceThreshold > 0, "invalid hedge price threshold"); require(_auctionTime > 0, "invalid auction time"); require(_minPriceMultiplier < 1e18, "min price multiplier too high"); require(_minPriceMultiplier > 0, "invalid min price multiplier"); require(_maxPriceMultiplier > 1e18, "max price multiplier too low"); oracle = _oracle; ethWSqueethPool = _ethWSqueethPool; hedgeTimeThreshold = _hedgeTimeThreshold; hedgePriceThreshold = _hedgePriceThreshold; auctionTime = _auctionTime; minPriceMultiplier = _minPriceMultiplier; maxPriceMultiplier = _maxPriceMultiplier; ethQuoteCurrencyPool = IController(_wSqueethController).ethQuoteCurrencyPool(); quoteCurrency = IController(_wSqueethController).quoteCurrency(); } /** * @notice receive function to allow ETH transfer to this contract */ receive() external payable { require(msg.sender == weth || msg.sender == address(powerTokenController), "Cannot receive eth"); } /** * @notice owner can set the strategy cap in ETH collateral terms * @dev deposits are rejected if it would put the strategy above the cap amount * @dev strategy collateral can be above the cap amount due to hedging activities * @param _capAmount the maximum strategy collateral in ETH, checked on deposits */ function setStrategyCap(uint256 _capAmount) external onlyOwner { strategyCap = _capAmount; emit SetStrategyCap(_capAmount); } /** * @notice called to redeem the net value of a vault post shutdown * @dev needs to be called 1 time before users can exit the strategy using withdrawShutdown */ function redeemShortShutdown() external { hasRedeemedInShutdown = true; powerTokenController.redeemShort(vaultId); } /** * @notice flash deposit into strategy, providing ETH, selling wSqueeth and receiving strategy tokens * @dev this function will execute a flash swap where it receives ETH, deposits and mints using flash swap proceeds and msg.value, and then repays the flash swap with wSqueeth * @dev _ethToDeposit must be less than msg.value plus the proceeds from the flash swap * @dev the difference between _ethToDeposit and msg.value provides the minimum that a user can receive for their sold wSqueeth * @param _ethToDeposit total ETH that will be deposited in to the strategy which is a combination of msg.value and flash swap proceeds */ function flashDeposit(uint256 _ethToDeposit) external payable nonReentrant { (uint256 cachedStrategyDebt, uint256 cachedStrategyCollateral) = _syncStrategyState(); _checkStrategyCap(_ethToDeposit, cachedStrategyCollateral); (uint256 wSqueethToMint, ) = _calcWsqueethToMintAndFee( _ethToDeposit, cachedStrategyDebt, cachedStrategyCollateral ); if (cachedStrategyDebt == 0 && cachedStrategyCollateral == 0) { // store hedge data as strategy is delta neutral at this point // only execute this upon first deposit uint256 wSqueethEthPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); timeAtLastHedge = block.timestamp; priceAtLastHedge = wSqueethEthPrice; } _exactInFlashSwap( wPowerPerp, weth, IUniswapV3Pool(ethWSqueethPool).fee(), wSqueethToMint, _ethToDeposit.sub(msg.value), uint8(FLASH_SOURCE.FLASH_DEPOSIT), abi.encodePacked(_ethToDeposit) ); emit FlashDeposit(msg.sender, _ethToDeposit, wSqueethToMint); } /** * @notice flash withdraw from strategy, providing strategy tokens, buying wSqueeth, burning and receiving ETH * @dev this function will execute a flash swap where it receives wSqueeth, burns, withdraws ETH and then repays the flash swap with ETH * @param _crabAmount strategy token amount to burn * @param _maxEthToPay maximum ETH to pay to buy back the owed wSqueeth debt */ function flashWithdraw(uint256 _crabAmount, uint256 _maxEthToPay) external nonReentrant { uint256 exactWSqueethNeeded = _getDebtFromStrategyAmount(_crabAmount); _exactOutFlashSwap( weth, wPowerPerp, IUniswapV3Pool(ethWSqueethPool).fee(), exactWSqueethNeeded, _maxEthToPay, uint8(FLASH_SOURCE.FLASH_WITHDRAW), abi.encodePacked(_crabAmount) ); emit FlashWithdraw(msg.sender, _crabAmount, exactWSqueethNeeded); } /** * @notice deposit ETH into strategy * @dev provide ETH, return wSqueeth and strategy token */ function deposit() external payable nonReentrant { uint256 amount = msg.value; (uint256 wSqueethToMint, uint256 depositorCrabAmount) = _deposit(msg.sender, amount, false); emit Deposit(msg.sender, wSqueethToMint, depositorCrabAmount); } /** * @notice withdraw WETH from strategy * @dev provide strategy tokens and wSqueeth, returns eth * @param _crabAmount amount of strategy token to burn */ function withdraw(uint256 _crabAmount) external nonReentrant { uint256 wSqueethAmount = _getDebtFromStrategyAmount(_crabAmount); uint256 ethToWithdraw = _withdraw(msg.sender, _crabAmount, wSqueethAmount, false); // send back ETH collateral payable(msg.sender).sendValue(ethToWithdraw); emit Withdraw(msg.sender, _crabAmount, wSqueethAmount, ethToWithdraw); } /** * @notice called to exit a vault if the Squeeth Power Perp contracts are shutdown * @param _crabAmount amount of strategy token to burn */ function withdrawShutdown(uint256 _crabAmount) external nonReentrant { require(powerTokenController.isShutDown(), "Squeeth contracts not shut down"); require(hasRedeemedInShutdown, "Crab must redeemShortShutdown"); uint256 strategyShare = _calcCrabRatio(_crabAmount, totalSupply()); uint256 ethToWithdraw = _calcEthToWithdraw(strategyShare, address(this).balance); _burn(msg.sender, _crabAmount); payable(msg.sender).sendValue(ethToWithdraw); emit WithdrawShutdown(msg.sender, _crabAmount, ethToWithdraw); } /** * @notice hedge startegy based on time threshold with uniswap arbing * @dev this function atomically hedges on uniswap and provides a bounty to the caller based on the difference * @dev between uniswap execution price and the price of the hedging auction * @param _minWSqueeth minimum WSqueeth amount the caller willing to receive if hedge auction is selling WSqueeth * @param _minEth minimum ETH amount the caller is willing to receive if hedge auction is buying WSqueeth */ function timeHedgeOnUniswap(uint256 _minWSqueeth, uint256 _minEth) external { (bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge(); require(isTimeHedgeAllowed, "Time hedging is not allowed"); _hedgeOnUniswap(auctionTriggerTime, _minWSqueeth, _minEth); emit TimeHedgeOnUniswap(msg.sender, block.timestamp, auctionTriggerTime, _minWSqueeth, _minEth); } /** * @notice hedge startegy based on price threshold with uniswap arbing * @dev this function atomically hedges on uniswap and provides a bounty to the caller based on the difference * @dev between uniswap execution price and the price of the hedging auction * @param _auctionTriggerTime the time when the price deviation threshold was exceeded and when the auction started * @param _minWSqueeth minimum WSqueeth amount the caller willing to receive if hedge auction is selling WSqueeth * @param _minEth minimum ETH amount the caller is willing to receive if hedge auction is buying WSqueeth */ function priceHedgeOnUniswap( uint256 _auctionTriggerTime, uint256 _minWSqueeth, uint256 _minEth ) external payable { require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed"); _hedgeOnUniswap(_auctionTriggerTime, _minWSqueeth, _minEth); emit PriceHedgeOnUniswap(msg.sender, block.timestamp, _auctionTriggerTime, _minWSqueeth, _minEth); } /** * @notice strategy hedging based on time threshold * @dev need to attach msg.value if buying WSqueeth * @param _isStrategySellingWSqueeth sell or buy auction, true for sell auction * @param _limitPrice hedger limit auction price, should be the max price when auction is sell auction, min price when it is a buy auction */ function timeHedge(bool _isStrategySellingWSqueeth, uint256 _limitPrice) external payable nonReentrant { (bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge(); require(isTimeHedgeAllowed, "Time hedging is not allowed"); _hedge(auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice); emit TimeHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, auctionTriggerTime); } /** * @notice strategy hedging based on price threshold * @dev need to attach msg.value if buying WSqueeth * @param _auctionTriggerTime the time when the price deviation threshold was exceeded and when the auction started * @param _isStrategySellingWSqueeth specify the direction of the trade that you expect, this choice impacts the limit price chosen * @param _limitPrice the min or max price that you will trade at, depending on if buying or selling */ function priceHedge( uint256 _auctionTriggerTime, bool _isStrategySellingWSqueeth, uint256 _limitPrice ) external payable nonReentrant { require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed"); _hedge(_auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice); emit PriceHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, _auctionTriggerTime); } /** * @notice check if hedging based on price threshold is allowed * @param _auctionTriggerTime the time when the price deviation threshold was exceeded and when the auction started * @return true if hedging is allowed */ function checkPriceHedge(uint256 _auctionTriggerTime) external view returns (bool) { return _isPriceHedge(_auctionTriggerTime); } /** * @notice check if hedging based on time threshold is allowed * @return isTimeHedgeAllowed true if hedging is allowed * @return auctionTriggertime auction trigger timestamp */ function checkTimeHedge() external view returns (bool, uint256) { return _isTimeHedge(); } /** * @notice get wSqueeth debt amount associated with strategy token amount * @param _crabAmount strategy token amount * @return wSqueeth amount */ function getWsqueethFromCrabAmount(uint256 _crabAmount) external view returns (uint256) { return _getDebtFromStrategyAmount(_crabAmount); } /** * @notice owner can set the delta hedge threshold as a percent scaled by 1e18 of ETH collateral * @dev the strategy will not allow a hedge if the trade size is below this threshold * @param _deltaHedgeThreshold minimum hedge size in a percent of ETH collateral */ function setDeltaHedgeThreshold(uint256 _deltaHedgeThreshold) external onlyOwner { deltaHedgeThreshold = _deltaHedgeThreshold; emit SetDeltaHedgeThreshold(_deltaHedgeThreshold); } /** * @notice owner can set the twap period in seconds that is used for calculating twaps for hedging * @param _hedgingTwapPeriod the twap period, in seconds */ function setHedgingTwapPeriod(uint32 _hedgingTwapPeriod) external onlyOwner { require(_hedgingTwapPeriod >= 180, "twap period is too short"); hedgingTwapPeriod = _hedgingTwapPeriod; emit SetHedgingTwapPeriod(_hedgingTwapPeriod); } /** * @notice owner can set the hedge time threshold in seconds that determines how often the strategy can be hedged * @param _hedgeTimeThreshold the hedge time threshold, in seconds */ function setHedgeTimeThreshold(uint256 _hedgeTimeThreshold) external onlyOwner { require(_hedgeTimeThreshold > 0, "invalid hedge time threshold"); hedgeTimeThreshold = _hedgeTimeThreshold; emit SetHedgeTimeThreshold(_hedgeTimeThreshold); } /** * @notice owner can set the hedge time threshold in percent, scaled by 1e18 that determines the deviation in wPowerPerp price that can trigger a rebalance * @param _hedgePriceThreshold the hedge price threshold, in percent, scaled by 1e18 */ function setHedgePriceThreshold(uint256 _hedgePriceThreshold) external onlyOwner { require(_hedgePriceThreshold > 0, "invalid hedge price threshold"); hedgePriceThreshold = _hedgePriceThreshold; emit SetHedgePriceThreshold(_hedgePriceThreshold); } /** * @notice owner can set the auction time, in seconds, that a hedge auction runs for * @param _auctionTime the length of the hedge auction in seconds */ function setAuctionTime(uint256 _auctionTime) external onlyOwner { require(_auctionTime > 0, "invalid auction time"); auctionTime = _auctionTime; emit SetAuctionTime(_auctionTime); } /** * @notice owner can set the min price multiplier in a percentage scaled by 1e18 (9e17 is 90%) * @dev the min price multiplier is multiplied by the TWAP price to get the intial auction price * @param _minPriceMultiplier the min price multiplier, a percentage, scaled by 1e18 */ function setMinPriceMultiplier(uint256 _minPriceMultiplier) external onlyOwner { require(_minPriceMultiplier < 1e18, "min price multiplier too high"); minPriceMultiplier = _minPriceMultiplier; emit SetMinPriceMultiplier(_minPriceMultiplier); } /** * @notice owner can set the max price multiplier in a percentage scaled by 1e18 (11e18 is 110%) * @dev the max price multiplier is multiplied by the TWAP price to get the final auction price * @param _maxPriceMultiplier the max price multiplier, a percentage, scaled by 1e18 */ function setMaxPriceMultiplier(uint256 _maxPriceMultiplier) external onlyOwner { require(_maxPriceMultiplier > 1e18, "max price multiplier too low"); maxPriceMultiplier = _maxPriceMultiplier; emit SetMaxPriceMultiplier(_maxPriceMultiplier); } /** * @notice get current auction details * @param _auctionTriggerTime timestamp where auction started * @return if strategy is selling wSqueeth, wSqueeth amount to auction, ETH proceeds, auction price, if auction direction has switched */ function getAuctionDetails(uint256 _auctionTriggerTime) external view returns ( bool, uint256, uint256, uint256, bool ) { (uint256 strategyDebt, uint256 ethDelta) = _syncStrategyState(); uint256 currentWSqueethPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); uint256 feeAdjustment = _calcFeeAdjustment(); (bool isSellingAuction, ) = _checkAuctionType(strategyDebt, ethDelta, currentWSqueethPrice, feeAdjustment); uint256 auctionWSqueethEthPrice = _getAuctionPrice(_auctionTriggerTime, currentWSqueethPrice, isSellingAuction); (bool isStillSellingAuction, uint256 wSqueethToAuction) = _checkAuctionType( strategyDebt, ethDelta, auctionWSqueethEthPrice, feeAdjustment ); bool isAuctionDirectionChanged = isSellingAuction != isStillSellingAuction; uint256 ethProceeds = wSqueethToAuction.wmul(auctionWSqueethEthPrice); return (isSellingAuction, wSqueethToAuction, ethProceeds, auctionWSqueethEthPrice, isAuctionDirectionChanged); } /** * @notice check if a user deposit puts the strategy above the cap * @dev reverts if a deposit amount puts strategy over the cap * @dev it is possible for the strategy to be over the cap from trading/hedging activities, but withdrawals are still allowed * @param _depositAmount the user deposit amount in ETH * @param _strategyCollateral the updated strategy collateral */ function _checkStrategyCap(uint256 _depositAmount, uint256 _strategyCollateral) internal view { require(_strategyCollateral.add(_depositAmount) <= strategyCap, "Deposit exceeds strategy cap"); } /** * @notice uniswap flash swap callback function * @dev this function will be called by flashswap callback function uniswapV3SwapCallback() * @param _caller address of original function caller * @param _amountToPay amount to pay back for flashswap * @param _callData arbitrary data attached to callback * @param _callSource identifier for which function triggered callback */ function _strategyFlash( address _caller, address, /*_tokenIn*/ address, /*_tokenOut*/ uint24, /*_fee*/ uint256 _amountToPay, bytes memory _callData, uint8 _callSource ) internal override { if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_DEPOSIT) { FlashDepositData memory data = abi.decode(_callData, (FlashDepositData)); // convert WETH to ETH as Uniswap uses WETH IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this))); //use user msg.value and unwrapped WETH from uniswap flash swap proceeds to deposit into strategy //will revert if data.totalDeposit is > eth balance in contract _deposit(_caller, data.totalDeposit, true); //repay the flash swap IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay); emit FlashDepositCallback(_caller, _amountToPay, address(this).balance); //return excess eth to the user that was not needed for slippage if (address(this).balance > 0) { payable(_caller).sendValue(address(this).balance); } } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_WITHDRAW) { FlashWithdrawData memory data = abi.decode(_callData, (FlashWithdrawData)); //use flash swap wSqueeth proceeds to withdraw ETH along with user crabAmount uint256 ethToWithdraw = _withdraw( _caller, data.crabAmount, IWPowerPerp(wPowerPerp).balanceOf(address(this)), true ); //use some amount of withdrawn ETH to repay flash swap IWETH9(weth).deposit{value: _amountToPay}(); IWETH9(weth).transfer(ethWSqueethPool, _amountToPay); //excess ETH not used to repay flash swap is transferred to the user uint256 proceeds = ethToWithdraw.sub(_amountToPay); emit FlashWithdrawCallback(_caller, _amountToPay, proceeds); if (proceeds > 0) { payable(_caller).sendValue(proceeds); } } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_SELL) { //strategy is selling wSqueeth for ETH FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData)); // convert WETH to ETH as Uniswap uses WETH IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this))); //mint wSqueeth to pay hedger and repay flash swap, deposit ETH _executeSellAuction(_caller, data.ethProceeds, data.wSqueethAmount, data.ethProceeds, true); //determine excess wSqueeth that the auction would have sold but is not needed to repay flash swap uint256 wSqueethProfit = data.wSqueethAmount.sub(_amountToPay); //minimum profit check for hedger require(wSqueethProfit >= data.minWSqueeth, "profit is less than min wSqueeth"); //repay flash swap and transfer profit to hedger IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay); IWPowerPerp(wPowerPerp).transfer(_caller, wSqueethProfit); } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_BUY) { //strategy is buying wSqueeth for ETH FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData)); //withdraw ETH to pay hedger and repay flash swap, burn wSqueeth _executeBuyAuction(_caller, data.wSqueethAmount, data.ethProceeds, true); //determine excess ETH that the auction would have paid but is not needed to repay flash swap uint256 ethProfit = data.ethProceeds.sub(_amountToPay); //minimum profit check for hedger require(ethProfit >= data.minEth, "profit is less than min ETH"); //repay flash swap and transfer profit to hedger IWETH9(weth).deposit{value: _amountToPay}(); IWETH9(weth).transfer(ethWSqueethPool, _amountToPay); payable(_caller).sendValue(ethProfit); } } /** * @notice deposit into strategy * @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user * @param _depositor depositor address * @param _amount amount of ETH collateral to deposit * @param _isFlashDeposit true if called by flashDeposit * @return wSqueethToMint minted amount of WSqueeth * @return depositorCrabAmount minted CRAB strategy token amount */ function _deposit( address _depositor, uint256 _amount, bool _isFlashDeposit ) internal returns (uint256, uint256) { (uint256 strategyDebt, uint256 strategyCollateral) = _syncStrategyState(); _checkStrategyCap(_amount, strategyCollateral); (uint256 wSqueethToMint, uint256 ethFee) = _calcWsqueethToMintAndFee(_amount, strategyDebt, strategyCollateral); uint256 depositorCrabAmount = _calcSharesToMint(_amount.sub(ethFee), strategyCollateral, totalSupply()); if (strategyDebt == 0 && strategyCollateral == 0) { // store hedge data as strategy is delta neutral at this point // only execute this upon first deposit uint256 wSqueethEthPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); timeAtLastHedge = block.timestamp; priceAtLastHedge = wSqueethEthPrice; } // mint wSqueeth and send it to msg.sender _mintWPowerPerp(_depositor, wSqueethToMint, _amount, _isFlashDeposit); // mint LP to depositor _mintStrategyToken(_depositor, depositorCrabAmount); return (wSqueethToMint, depositorCrabAmount); } /** * @notice withdraw WETH from strategy * @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user * @param _crabAmount amount of strategy token to burn * @param _wSqueethAmount amount of wSqueeth to burn * @param _isFlashWithdraw flag if called by flashWithdraw * @return ETH amount to withdraw */ function _withdraw( address _from, uint256 _crabAmount, uint256 _wSqueethAmount, bool _isFlashWithdraw ) internal returns (uint256) { (, uint256 strategyCollateral) = _syncStrategyState(); uint256 strategyShare = _calcCrabRatio(_crabAmount, totalSupply()); uint256 ethToWithdraw = _calcEthToWithdraw(strategyShare, strategyCollateral); _burnWPowerPerp(_from, _wSqueethAmount, ethToWithdraw, _isFlashWithdraw); _burn(_from, _crabAmount); return ethToWithdraw; } /** * @notice hedging function to adjust collateral and debt to be eth delta neutral * @param _auctionTriggerTime timestamp where auction started * @param _isStrategySellingWSqueeth auction type, true for sell auction * @param _limitPrice hedger accepted auction price, should be the max price when auction is sell auction, min price when it is a buy auction */ function _hedge( uint256 _auctionTriggerTime, bool _isStrategySellingWSqueeth, uint256 _limitPrice ) internal { ( bool isSellingAuction, uint256 wSqueethToAuction, uint256 ethProceeds, uint256 auctionWSqueethEthPrice ) = _startAuction(_auctionTriggerTime); require(_isStrategySellingWSqueeth == isSellingAuction, "wrong auction type"); if (isSellingAuction) { // Receiving ETH and paying wSqueeth require(auctionWSqueethEthPrice <= _limitPrice, "Auction price > max price"); require(msg.value >= ethProceeds, "Low ETH amount received"); _executeSellAuction(msg.sender, msg.value, wSqueethToAuction, ethProceeds, false); } else { require(msg.value == 0, "ETH attached for buy auction"); // Receiving wSqueeth and paying ETH require(auctionWSqueethEthPrice >= _limitPrice, "Auction price < min price"); _executeBuyAuction(msg.sender, wSqueethToAuction, ethProceeds, false); } emit Hedge( msg.sender, _isStrategySellingWSqueeth, _limitPrice, auctionWSqueethEthPrice, wSqueethToAuction, ethProceeds ); } /** * @notice execute arb between auction price and uniswap price * @param _auctionTriggerTime auction starting time * @param _minWSqueeth minimum WSqueeth amount the caller willing to receive if hedge auction is selling WSqueeth * @param _minEth minimum ETH amount the caller is willing to receive if hedge auction is buying WSqueeth */ function _hedgeOnUniswap( uint256 _auctionTriggerTime, uint256 _minWSqueeth, uint256 _minEth ) internal { ( bool isSellingAuction, uint256 wSqueethToAuction, uint256 ethProceeds, uint256 auctionWSqueethEthPrice ) = _startAuction(_auctionTriggerTime); if (isSellingAuction) { _exactOutFlashSwap( wPowerPerp, weth, IUniswapV3Pool(ethWSqueethPool).fee(), ethProceeds, wSqueethToAuction, uint8(FLASH_SOURCE.FLASH_HEDGE_SELL), abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth) ); } else { _exactOutFlashSwap( weth, wPowerPerp, IUniswapV3Pool(ethWSqueethPool).fee(), wSqueethToAuction, ethProceeds, uint8(FLASH_SOURCE.FLASH_HEDGE_BUY), abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth) ); } emit HedgeOnUniswap(msg.sender, isSellingAuction, auctionWSqueethEthPrice, wSqueethToAuction, ethProceeds); } /** * @notice execute sell auction based on the parameters calculated * @dev if _isHedgingOnUniswap, wSqueeth minted is kept to repay flashswap, otherwise sent to seller * @param _buyer buyer address * @param _buyerAmount buyer ETH amount sent * @param _wSqueethToSell wSqueeth amount to sell * @param _ethToBuy ETH amount to buy * @param _isHedgingOnUniswap true if arbing with uniswap price */ function _executeSellAuction( address _buyer, uint256 _buyerAmount, uint256 _wSqueethToSell, uint256 _ethToBuy, bool _isHedgingOnUniswap ) internal { if (_isHedgingOnUniswap) { _mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, true); } else { _mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, false); uint256 remainingEth = _buyerAmount.sub(_ethToBuy); if (remainingEth > 0) { payable(_buyer).sendValue(remainingEth); } } emit ExecuteSellAuction(_buyer, _wSqueethToSell, _ethToBuy, _isHedgingOnUniswap); } /** * @notice execute buy auction based on the parameters calculated * @dev if _isHedgingOnUniswap, ETH proceeds are not sent to seller * @param _seller seller address * @param _wSqueethToBuy wSqueeth amount to buy * @param _ethToSell ETH amount to sell * @param _isHedgingOnUniswap true if arbing with uniswap price */ function _executeBuyAuction( address _seller, uint256 _wSqueethToBuy, uint256 _ethToSell, bool _isHedgingOnUniswap ) internal { _burnWPowerPerp(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap); if (!_isHedgingOnUniswap) { payable(_seller).sendValue(_ethToSell); } emit ExecuteBuyAuction(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap); } /** * @notice determine auction direction, price, and ensure auction hasn't switched directions * @param _auctionTriggerTime auction starting time * @return auction type * @return WSqueeth amount to sell or buy * @return ETH to sell/buy * @return auction WSqueeth/ETH price */ function _startAuction(uint256 _auctionTriggerTime) internal returns ( bool, uint256, uint256, uint256 ) { (uint256 strategyDebt, uint256 ethDelta) = _syncStrategyState(); uint256 currentWSqueethPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); uint256 feeAdjustment = _calcFeeAdjustment(); (bool isSellingAuction, ) = _checkAuctionType(strategyDebt, ethDelta, currentWSqueethPrice, feeAdjustment); uint256 auctionWSqueethEthPrice = _getAuctionPrice(_auctionTriggerTime, currentWSqueethPrice, isSellingAuction); (bool isStillSellingAuction, uint256 wSqueethToAuction) = _checkAuctionType( strategyDebt, ethDelta, auctionWSqueethEthPrice, feeAdjustment ); require(isSellingAuction == isStillSellingAuction, "auction direction changed"); uint256 ethProceeds = wSqueethToAuction.wmul(auctionWSqueethEthPrice); timeAtLastHedge = block.timestamp; priceAtLastHedge = currentWSqueethPrice; return (isSellingAuction, wSqueethToAuction, ethProceeds, auctionWSqueethEthPrice); } /** * @notice sync strategy debt and collateral amount from vault * @return synced debt amount * @return synced collateral amount */ function _syncStrategyState() internal view returns (uint256, uint256) { (, , uint256 syncedStrategyCollateral, uint256 syncedStrategyDebt) = _getVaultDetails(); return (syncedStrategyDebt, syncedStrategyCollateral); } /** * @notice calculate the fee adjustment factor, which is the amount of ETH owed per 1 wSqueeth minted * @dev the fee is a based off the index value of squeeth and uses a twap scaled down by the PowerPerp's INDEX_SCALE * @return the fee adjustment factor */ function _calcFeeAdjustment() internal view returns (uint256) { uint256 wSqueethEthPrice = Power2Base._getTwap( oracle, ethWSqueethPool, wPowerPerp, weth, POWER_PERP_PERIOD, false ); uint256 feeRate = IController(powerTokenController).feeRate(); return wSqueethEthPrice.mul(feeRate).div(10000); } /** * @notice calculate amount of wSqueeth to mint and fee paid from deposited amount * @param _depositedAmount amount of deposited WETH * @param _strategyDebtAmount amount of strategy debt * @param _strategyCollateralAmount collateral amount in strategy * @return amount of minted wSqueeth and ETH fee paid on minted squeeth */ function _calcWsqueethToMintAndFee( uint256 _depositedAmount, uint256 _strategyDebtAmount, uint256 _strategyCollateralAmount ) internal view returns (uint256, uint256) { uint256 wSqueethToMint; uint256 feeAdjustment = _calcFeeAdjustment(); if (_strategyDebtAmount == 0 && _strategyCollateralAmount == 0) { require(totalSupply() == 0, "Crab contracts shut down"); uint256 wSqueethEthPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); uint256 squeethDelta = wSqueethEthPrice.wmul(2e18); wSqueethToMint = _depositedAmount.wdiv(squeethDelta.add(feeAdjustment)); } else { wSqueethToMint = _depositedAmount.wmul(_strategyDebtAmount).wdiv( _strategyCollateralAmount.add(_strategyDebtAmount.wmul(feeAdjustment)) ); } uint256 fee = wSqueethToMint.wmul(feeAdjustment); return (wSqueethToMint, fee); } /** * @notice check if hedging based on time threshold is allowed * @return true if time hedging is allowed * @return auction trigger timestamp */ function _isTimeHedge() internal view returns (bool, uint256) { uint256 auctionTriggerTime = timeAtLastHedge.add(hedgeTimeThreshold); return (block.timestamp >= auctionTriggerTime, auctionTriggerTime); } /** * @notice check if hedging based on price threshold is allowed * @param _auctionTriggerTime timestamp where auction started * @return true if hedging is allowed */ function _isPriceHedge(uint256 _auctionTriggerTime) internal view returns (bool) { if (_auctionTriggerTime < timeAtLastHedge) return false; uint32 secondsToPriceHedgeTrigger = uint32(block.timestamp.sub(_auctionTriggerTime)); uint256 wSqueethEthPriceAtTriggerTime = IOracle(oracle).getHistoricalTwap( ethWSqueethPool, wPowerPerp, weth, secondsToPriceHedgeTrigger + hedgingTwapPeriod, secondsToPriceHedgeTrigger ); uint256 cachedRatio = wSqueethEthPriceAtTriggerTime.wdiv(priceAtLastHedge); uint256 priceThreshold = cachedRatio > 1e18 ? (cachedRatio).sub(1e18) : uint256(1e18).sub(cachedRatio); return priceThreshold >= hedgePriceThreshold; } /** * @notice calculate auction price based on auction direction, start time and wSqueeth price * @param _auctionTriggerTime timestamp where auction started * @param _wSqueethEthPrice WSqueeth/ETH price * @param _isSellingAuction auction type (true for selling, false for buying auction) * @return auction price */ function _getAuctionPrice( uint256 _auctionTriggerTime, uint256 _wSqueethEthPrice, bool _isSellingAuction ) internal view returns (uint256) { uint256 auctionCompletionRatio = block.timestamp.sub(_auctionTriggerTime) >= auctionTime ? 1e18 : (block.timestamp.sub(_auctionTriggerTime)).wdiv(auctionTime); uint256 priceMultiplier; if (_isSellingAuction) { priceMultiplier = maxPriceMultiplier.sub( auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier)) ); } else { priceMultiplier = minPriceMultiplier.add( auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier)) ); } return _wSqueethEthPrice.wmul(priceMultiplier); } /** * @notice check the direction of auction and the target amount of wSqueeth to hedge * @param _debt strategy debt * @param _ethDelta ETH delta (amount of ETH in strategy) * @param _wSqueethEthPrice WSqueeth/ETH price * @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted * @return auction type(sell or buy) and auction initial target hedge in wSqueeth */ function _checkAuctionType( uint256 _debt, uint256 _ethDelta, uint256 _wSqueethEthPrice, uint256 _feeAdjustment ) internal view returns (bool, uint256) { uint256 wSqueethDelta = _debt.wmul(2e18).wmul(_wSqueethEthPrice); (uint256 targetHedge, bool isSellingAuction) = _getTargetHedgeAndAuctionType( wSqueethDelta, _ethDelta, _wSqueethEthPrice, _feeAdjustment ); require(targetHedge.wmul(_wSqueethEthPrice).wdiv(_ethDelta) > deltaHedgeThreshold, "strategy is delta neutral"); return (isSellingAuction, targetHedge); } /** * @dev calculate amount of strategy token to mint for depositor * @param _amount amount of ETH deposited * @param _strategyCollateralAmount amount of strategy collateral * @param _crabTotalSupply total supply of strategy token * @return amount of strategy token to mint */ function _calcSharesToMint( uint256 _amount, uint256 _strategyCollateralAmount, uint256 _crabTotalSupply ) internal pure returns (uint256) { uint256 depositorShare = _amount.wdiv(_strategyCollateralAmount.add(_amount)); if (_crabTotalSupply != 0) return _crabTotalSupply.wmul(depositorShare).wdiv(uint256(1e18).sub(depositorShare)); return _amount; } /** * @notice calculates the ownership proportion for strategy debt and collateral relative to a total amount of strategy tokens * @param _crabAmount strategy token amount * @param _totalSupply strategy total supply * @return ownership proportion of a strategy token amount relative to the total strategy tokens */ function _calcCrabRatio(uint256 _crabAmount, uint256 _totalSupply) internal pure returns (uint256) { return _crabAmount.wdiv(_totalSupply); } /** * @notice calculate ETH to withdraw from strategy given a ownership proportion * @param _crabRatio crab ratio * @param _strategyCollateralAmount amount of collateral in strategy * @return amount of ETH allowed to withdraw */ function _calcEthToWithdraw(uint256 _crabRatio, uint256 _strategyCollateralAmount) internal pure returns (uint256) { return _strategyCollateralAmount.wmul(_crabRatio); } /** * @notice determine target hedge and auction type (selling/buying auction) * @dev target hedge is the amount of WSqueeth the auction needs to sell or buy to be eth delta neutral * @param _wSqueethDelta WSqueeth delta * @param _ethDelta ETH delta * @param _wSqueethEthPrice WSqueeth/ETH price * @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted * @return target hedge in wSqueeth * @return auction type: true if auction is selling WSqueeth, false if buying WSqueeth */ function _getTargetHedgeAndAuctionType( uint256 _wSqueethDelta, uint256 _ethDelta, uint256 _wSqueethEthPrice, uint256 _feeAdjustment ) internal pure returns (uint256, bool) { return (_wSqueethDelta > _ethDelta) ? ((_wSqueethDelta.sub(_ethDelta)).wdiv(_wSqueethEthPrice), false) : ((_ethDelta.sub(_wSqueethDelta)).wdiv(_wSqueethEthPrice.add(_feeAdjustment)), true); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import {VaultLib} from "../libs/VaultLib.sol"; interface IController { function ethQuoteCurrencyPool() external view returns (address); function feeRate() external view returns (uint256); function getFee( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _collateralAmount ) external view returns (uint256); function quoteCurrency() external view returns (address); function vaults(uint256 _vaultId) external view returns (VaultLib.Vault memory); function shortPowerPerp() external view returns (address); function wPowerPerp() external view returns (address); function getExpectedNormalizationFactor() external view returns (uint256); function mintPowerPerpAmount( uint256 _vaultId, uint256 _powerPerpAmount, uint256 _uniTokenId ) external payable returns (uint256 vaultId, uint256 wPowerPerpAmount); function mintWPowerPerpAmount( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _uniTokenId ) external payable returns (uint256 vaultId); /** * Deposit collateral into a vault */ function deposit(uint256 _vaultId) external payable; /** * Withdraw collateral from a vault. */ function withdraw(uint256 _vaultId, uint256 _amount) external payable; function burnWPowerPerpAmount( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _withdrawAmount ) external; function burnOnPowerPerpAmount( uint256 _vaultId, uint256 _powerPerpAmount, uint256 _withdrawAmount ) external returns (uint256 wPowerPerpAmount); function liquidate(uint256 _vaultId, uint256 _maxDebtAmount) external returns (uint256); function updateOperator(uint256 _vaultId, address _operator) external; /** * External function to update the normalized factor as a way to pay funding. */ function applyFunding() external; function redeemShort(uint256 _vaultId) external; function reduceDebtShutdown(uint256 _vaultId) external; function isShutDown() external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWPowerPerp is IERC20 { function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; interface IOracle { function getHistoricalTwap( address _pool, address _base, address _quote, uint32 _period, uint32 _periodToHistoricPrice ) external view returns (uint256); function getTwap( address _pool, address _base, address _quote, uint32 _period, bool _checkPeriod ) external view returns (uint256); function getMaxPeriod(address _pool) external view returns (uint32); function getTimeWeightedAverageTickSafe(address _pool, uint32 _period) external view returns (int24 timeWeightedAverageTick); } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH9 is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: GPL-3.0-only pragma solidity =0.7.6; pragma abicoder v2; // interface import {IController} from "../../interfaces/IController.sol"; import {IWPowerPerp} from "../../interfaces/IWPowerPerp.sol"; // contract import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // lib import {Address} from "@openzeppelin/contracts/utils/Address.sol"; // StrategyMath licensed under AGPL-3.0-only import {StrategyMath} from "./StrategyMath.sol"; import {VaultLib} from "../../libs/VaultLib.sol"; /** * @dev StrategyBase contract * @notice base contract for PowerToken strategy * @author opyn team */ contract StrategyBase is ERC20 { using StrategyMath for uint256; using Address for address payable; /// @dev power token controller IController public powerTokenController; /// @dev WETH token address public immutable weth; address public immutable wPowerPerp; /// @dev power token strategy vault ID uint256 public immutable vaultId; /** * @notice constructor for StrategyBase * @dev this will open a vault in the power token contract and store the vault ID * @param _powerTokenController power token controller address * @param _weth weth token address * @param _name token name for strategy ERC20 token * @param _symbol token symbol for strategy ERC20 token */ constructor(address _powerTokenController, address _weth, string memory _name, string memory _symbol) ERC20(_name, _symbol) { require(_powerTokenController != address(0), "invalid controller address"); require(_weth != address(0), "invalid weth address"); weth = _weth; powerTokenController = IController(_powerTokenController); wPowerPerp = address(powerTokenController.wPowerPerp()); vaultId = powerTokenController.mintWPowerPerpAmount(0, 0, 0); } /** * @notice get power token strategy vault ID * @return vault ID */ function getStrategyVaultId() external view returns (uint256) { return vaultId; } /** * @notice get the vault composition of the strategy * @return operator * @return nft collateral id * @return collateral amount * @return short amount */ function getVaultDetails() external view returns (address, uint256, uint256, uint256) { return _getVaultDetails(); } /** * @notice mint WPowerPerp and deposit collateral * @dev this function will not send WPowerPerp to msg.sender if _keepWSqueeth == true * @param _to receiver address * @param _wAmount amount of WPowerPerp to mint * @param _collateral amount of collateral to deposit * @param _keepWsqueeth keep minted wSqueeth in this contract if it is set to true */ function _mintWPowerPerp( address _to, uint256 _wAmount, uint256 _collateral, bool _keepWsqueeth ) internal { powerTokenController.mintWPowerPerpAmount{value: _collateral}(vaultId, _wAmount, 0); if (!_keepWsqueeth) { IWPowerPerp(wPowerPerp).transfer(_to, _wAmount); } } /** * @notice burn WPowerPerp and withdraw collateral * @dev this function will not take WPowerPerp from msg.sender if _isOwnedWSqueeth == true * @param _from WPowerPerp holder address * @param _amount amount of wPowerPerp to burn * @param _collateralToWithdraw amount of collateral to withdraw * @param _isOwnedWSqueeth transfer WPowerPerp from holder if it is set to false */ function _burnWPowerPerp( address _from, uint256 _amount, uint256 _collateralToWithdraw, bool _isOwnedWSqueeth ) internal { if (!_isOwnedWSqueeth) { IWPowerPerp(wPowerPerp).transferFrom(_from, address(this), _amount); } powerTokenController.burnWPowerPerpAmount(vaultId, _amount, _collateralToWithdraw); } /** * @notice mint strategy token * @param _to recepient address * @param _amount token amount */ function _mintStrategyToken(address _to, uint256 _amount) internal { _mint(_to, _amount); } /** * @notice get strategy debt amount for a specific strategy token amount * @param _strategyAmount strategy amount * @return debt amount */ function _getDebtFromStrategyAmount(uint256 _strategyAmount) internal view returns (uint256) { (, , ,uint256 strategyDebt) = _getVaultDetails(); return strategyDebt.wmul(_strategyAmount).wdiv(totalSupply()); } /** * @notice get the vault composition of the strategy * @return operator * @return nft collateral id * @return collateral amount * @return short amount */ function _getVaultDetails() internal view returns (address, uint256, uint256, uint256) { VaultLib.Vault memory strategyVault = powerTokenController.vaults(vaultId); return (strategyVault.operator, strategyVault.NftCollateralId, strategyVault.collateralAmount, strategyVault.shortAmount); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; // interface import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; // lib import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import '@uniswap/v3-periphery/contracts/libraries/Path.sol'; import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/libraries/SafeCast.sol'; contract StrategyFlashSwap is IUniswapV3SwapCallback { using Path for bytes; using SafeCast for uint256; using LowGasSafeMath for uint256; using LowGasSafeMath for int256; /// @dev Uniswap factory address address public immutable factory; struct SwapCallbackData { bytes path; address caller; uint8 callSource; bytes callData; } /** * @dev constructor * @param _factory uniswap factory address */ constructor( address _factory ) { require(_factory != address(0), "invalid factory address"); factory = _factory; } /** * @notice uniswap swap callback function for flashes * @param amount0Delta amount of token0 * @param amount1Delta amount of token1 * @param _data callback data encoded as SwapCallbackData struct */ function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata _data ) external override { require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); //ensure that callback comes from uniswap pool CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee); //determine the amount that needs to be repaid as part of the flashswap uint256 amountToPay = amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); //calls the strategy function that uses the proceeds from flash swap and executes logic to have an amount of token to repay the flash swap _strategyFlash(data.caller, tokenIn, tokenOut, fee, amountToPay, data.callData, data.callSource); } /** * @notice execute an exact-in flash swap (specify an exact amount to pay) * @param _tokenIn token address to sell * @param _tokenOut token address to receive * @param _fee pool fee * @param _amountIn amount to sell * @param _amountOutMinimum minimum amount to receive * @param _callSource function call source * @param _data arbitrary data assigned with the call */ function _exactInFlashSwap(address _tokenIn, address _tokenOut, uint24 _fee, uint256 _amountIn, uint256 _amountOutMinimum, uint8 _callSource, bytes memory _data) internal { //calls internal uniswap swap function that will trigger a callback for the flash swap uint256 amountOut = _exactInputInternal( _amountIn, address(this), uint160(0), SwapCallbackData({path: abi.encodePacked(_tokenIn, _fee, _tokenOut), caller: msg.sender, callSource: _callSource, callData: _data}) ); //slippage limit check require(amountOut >= _amountOutMinimum, "amount out less than min"); } /** * @notice execute an exact-out flash swap (specify an exact amount to receive) * @param _tokenIn token address to sell * @param _tokenOut token address to receive * @param _fee pool fee * @param _amountOut exact amount to receive * @param _amountInMaximum maximum amount to sell * @param _callSource function call source * @param _data arbitrary data assigned with the call */ function _exactOutFlashSwap(address _tokenIn, address _tokenOut, uint24 _fee, uint256 _amountOut, uint256 _amountInMaximum, uint8 _callSource, bytes memory _data) internal { //calls internal uniswap swap function that will trigger a callback for the flash swap uint256 amountIn = _exactOutputInternal( _amountOut, address(this), uint160(0), SwapCallbackData({path: abi.encodePacked(_tokenOut, _fee, _tokenIn), caller: msg.sender, callSource: _callSource, callData: _data}) ); //slippage limit check require(amountIn <= _amountInMaximum, "amount in greater than max"); } /** * @notice function to be called by uniswap callback. * @dev this function should be overridden by the child contract * param _caller initial strategy function caller * param _tokenIn token address sold * param _tokenOut token address bought * param _fee pool fee * param _amountToPay amount to pay for the pool second token * param _callData arbitrary data assigned with the flashswap call * param _callSource function call source */ function _strategyFlash(address /*_caller*/, address /*_tokenIn*/, address /*_tokenOut*/, uint24 /*_fee*/, uint256 /*_amountToPay*/, bytes memory _callData, uint8 _callSource) internal virtual {} /** * @notice internal function for exact-in swap on uniswap (specify exact amount to pay) * @param _amountIn amount of token to pay * @param _recipient recipient for receive * @param _sqrtPriceLimitX96 price limit * @return amount of token bought (amountOut) */ function _exactInputInternal( uint256 _amountIn, address _recipient, uint160 _sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256) { (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); //uniswap token0 has a lower address than token1 //if tokenIn<tokenOut, we are selling an exact amount of token0 in exchange for token1 //zeroForOne determines which token is being sold and which is being bought bool zeroForOne = tokenIn < tokenOut; //swap on uniswap, including data to trigger call back for flashswap (int256 amount0, int256 amount1) = _getPool(tokenIn, tokenOut, fee).swap( _recipient, zeroForOne, _amountIn.toInt256(), _sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : _sqrtPriceLimitX96, abi.encode(data) ); //determine the amountOut based on which token has a lower address return uint256(-(zeroForOne ? amount1 : amount0)); } /** * @notice internal function for exact-out swap on uniswap (specify exact amount to receive) * @param _amountOut amount of token to receive * @param _recipient recipient for receive * @param _sqrtPriceLimitX96 price limit * @return amount of token sold (amountIn) */ function _exactOutputInternal( uint256 _amountOut, address _recipient, uint160 _sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256) { (address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool(); //uniswap token0 has a lower address than token1 //if tokenIn<tokenOut, we are buying an exact amount of token1 in exchange for token0 //zeroForOne determines which token is being sold and which is being bought bool zeroForOne = tokenIn < tokenOut; //swap on uniswap, including data to trigger call back for flashswap (int256 amount0Delta, int256 amount1Delta) = _getPool(tokenIn, tokenOut, fee).swap( _recipient, zeroForOne, -_amountOut.toInt256(), _sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : _sqrtPriceLimitX96, abi.encode(data) ); //determine the amountIn and amountOut based on which token has a lower address (uint256 amountIn, uint256 amountOutReceived) = zeroForOne ? (uint256(amount0Delta), uint256(-amount1Delta)) : (uint256(amount1Delta), uint256(-amount0Delta)); // it's technically possible to not receive the full output amount, // so if no price limit has been specified, require this possibility away if (_sqrtPriceLimitX96 == 0) require(amountOutReceived == _amountOut); return amountIn; } /** * @notice returns the uniswap pool for the given token pair and fee * @dev the pool contract may or may not exist * @param tokenA address of first token * @param tokenB address of second token * @param fee fee tier for pool */ function _getPool( address tokenA, address tokenB, uint24 fee ) private view returns (IUniswapV3Pool) { return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee))); } } // 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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } //SPDX-License-Identifier: AGPL-3.0-only /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >0.4.13; /** * @notice Copied from https://github.com/dapphub/ds-math/blob/e70a364787804c1ded9801ed6c27b440a86ebd32/src/math.sol * @dev change contract to library, added div() function */ library StrategyMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; //interface import {IOracle} from "../interfaces/IOracle.sol"; //lib import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; library Power2Base { using SafeMath for uint256; uint32 private constant TWAP_PERIOD = 420 seconds; uint256 private constant INDEX_SCALE = 1e4; uint256 private constant ONE = 1e18; uint256 private constant ONE_ONE = 1e36; /** * @notice return the scaled down index of the power perp in USD, scaled by 18 decimals * @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool) * @param _oracle oracle address * @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency * @param _weth weth address * @param _quoteCurrency quoteCurrency address * @return for squeeth, return ethPrice^2 */ function _getIndex( uint32 _period, address _oracle, address _ethQuoteCurrencyPool, address _weth, address _quoteCurrency ) internal view returns (uint256) { uint256 ethQuoteCurrencyPrice = _getScaledTwap( _oracle, _ethQuoteCurrencyPool, _weth, _quoteCurrency, _period, false ); return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE); } /** * @notice return the unscaled index of the power perp in USD, scaled by 18 decimals * @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool) * @param _oracle oracle address * @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency * @param _weth weth address * @param _quoteCurrency quoteCurrency address * @return for squeeth, return ethPrice^2 */ function _getUnscaledIndex( uint32 _period, address _oracle, address _ethQuoteCurrencyPool, address _weth, address _quoteCurrency ) internal view returns (uint256) { uint256 ethQuoteCurrencyPrice = _getTwap(_oracle, _ethQuoteCurrencyPool, _weth, _quoteCurrency, _period, false); return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE); } /** * @notice return the mark price of power perp in quoteCurrency, scaled by 18 decimals * @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool) * @param _oracle oracle address * @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth * @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency * @param _weth weth address * @param _quoteCurrency quoteCurrency address * @param _wSqueeth wSqueeth address * @param _normalizationFactor current normalization factor * @return for squeeth, return ethPrice * squeethPriceInEth */ function _getDenormalizedMark( uint32 _period, address _oracle, address _wSqueethEthPool, address _ethQuoteCurrencyPool, address _weth, address _quoteCurrency, address _wSqueeth, uint256 _normalizationFactor ) internal view returns (uint256) { uint256 ethQuoteCurrencyPrice = _getScaledTwap( _oracle, _ethQuoteCurrencyPool, _weth, _quoteCurrency, _period, false ); uint256 wsqueethEthPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, _period, false); return wsqueethEthPrice.mul(ethQuoteCurrencyPrice).div(_normalizationFactor); } /** * @notice get the fair collateral value for a _debtAmount of wSqueeth * @dev the actual amount liquidator can get should have a 10% bonus on top of this value. * @param _debtAmount wSqueeth amount paid by liquidator * @param _oracle oracle address * @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth * @param _wSqueeth wSqueeth address * @param _weth weth address * @return returns value of debt in ETH */ function _getDebtValueInEth( uint256 _debtAmount, address _oracle, address _wSqueethEthPool, address _wSqueeth, address _weth ) internal view returns (uint256) { uint256 wSqueethPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, TWAP_PERIOD, false); return _debtAmount.mul(wSqueethPrice).div(ONE); } /** * @notice request twap from our oracle, scaled down by INDEX_SCALE * @param _oracle oracle address * @param _pool uniswap v3 pool address * @param _base base currency. to get eth/usd price, eth is base token * @param _quote quote currency. to get eth/usd price, usd is the quote currency * @param _period number of seconds in the past to start calculating time-weighted average. * @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts * @return twap price scaled down by INDEX_SCALE */ function _getScaledTwap( address _oracle, address _pool, address _base, address _quote, uint32 _period, bool _checkPeriod ) internal view returns (uint256) { uint256 twap = _getTwap(_oracle, _pool, _base, _quote, _period, _checkPeriod); return twap.div(INDEX_SCALE); } /** * @notice request twap from our oracle * @dev this will revert if period is > max period for the pool * @param _oracle oracle address * @param _pool uniswap v3 pool address * @param _base base currency. to get eth/quoteCurrency price, eth is base token * @param _quote quote currency. to get eth/quoteCurrency price, quoteCurrency is the quote currency * @param _period number of seconds in the past to start calculating time-weighted average * @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts * @return human readable price. scaled by 1e18 */ function _getTwap( address _oracle, address _pool, address _base, address _quote, uint32 _period, bool _checkPeriod ) internal view returns (uint256) { // period reaching this point should be check, otherwise might revert return IOracle(_oracle).getTwap(_pool, _base, _quote, _period, _checkPeriod); } /** * @notice get the index value of wsqueeth in wei, used when system settles * @dev the index of squeeth is ethPrice^2, so each squeeth will need to pay out {ethPrice} eth * @param _wsqueethAmount amount of wsqueeth used in settlement * @param _indexPriceForSettlement index price for settlement * @param _normalizationFactor current normalization factor * @return amount in wei that should be paid to the token holder */ function _getLongSettlementValue( uint256 _wsqueethAmount, uint256 _indexPriceForSettlement, uint256 _normalizationFactor ) internal pure returns (uint256) { return _wsqueethAmount.mul(_normalizationFactor).mul(_indexPriceForSettlement).div(ONE_ONE); } } //SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; //interface import {INonfungiblePositionManager} from "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; //lib import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {TickMathExternal} from "./TickMathExternal.sol"; import {SqrtPriceMathPartial} from "./SqrtPriceMathPartial.sol"; import {Uint256Casting} from "./Uint256Casting.sol"; /** * Error code: * V1: Vault already had nft * V2: Vault has no NFT */ library VaultLib { using SafeMath for uint256; using Uint256Casting for uint256; uint256 constant ONE_ONE = 1e36; // the collateralization ratio (CR) is checked with the numerator and denominator separately // a user is safe if - collateral value >= (COLLAT_RATIO_NUMER/COLLAT_RATIO_DENOM)* debt value uint256 public constant CR_NUMERATOR = 3; uint256 public constant CR_DENOMINATOR = 2; struct Vault { // the address that can update the vault address operator; // uniswap position token id deposited into the vault as collateral // 2^32 is 4,294,967,296, which means the vault structure will work with up to 4 billion positions uint32 NftCollateralId; // amount of eth (wei) used in the vault as collateral // 2^96 / 1e18 = 79,228,162,514, which means a vault can store up to 79 billion eth // when we need to do calculations, we always cast this number to uint256 to avoid overflow uint96 collateralAmount; // amount of wPowerPerp minted from the vault uint128 shortAmount; } /** * @notice add eth collateral to a vault * @param _vault in-memory vault * @param _amount amount of eth to add */ function addEthCollateral(Vault memory _vault, uint256 _amount) internal pure { _vault.collateralAmount = uint256(_vault.collateralAmount).add(_amount).toUint96(); } /** * @notice add uniswap position token collateral to a vault * @param _vault in-memory vault * @param _tokenId uniswap position token id */ function addUniNftCollateral(Vault memory _vault, uint256 _tokenId) internal pure { require(_vault.NftCollateralId == 0, "V1"); require(_tokenId != 0, "C23"); _vault.NftCollateralId = _tokenId.toUint32(); } /** * @notice remove eth collateral from a vault * @param _vault in-memory vault * @param _amount amount of eth to remove */ function removeEthCollateral(Vault memory _vault, uint256 _amount) internal pure { _vault.collateralAmount = uint256(_vault.collateralAmount).sub(_amount).toUint96(); } /** * @notice remove uniswap position token collateral from a vault * @param _vault in-memory vault */ function removeUniNftCollateral(Vault memory _vault) internal pure { require(_vault.NftCollateralId != 0, "V2"); _vault.NftCollateralId = 0; } /** * @notice add debt to vault * @param _vault in-memory vault * @param _amount amount of debt to add */ function addShort(Vault memory _vault, uint256 _amount) internal pure { _vault.shortAmount = uint256(_vault.shortAmount).add(_amount).toUint128(); } /** * @notice remove debt from vault * @param _vault in-memory vault * @param _amount amount of debt to remove */ function removeShort(Vault memory _vault, uint256 _amount) internal pure { _vault.shortAmount = uint256(_vault.shortAmount).sub(_amount).toUint128(); } /** * @notice check if a vault is properly collateralized * @param _vault the vault we want to check * @param _positionManager address of the uniswap position manager * @param _normalizationFactor current _normalizationFactor * @param _ethQuoteCurrencyPrice current eth price scaled by 1e18 * @param _minCollateral minimum collateral that needs to be in a vault * @param _wsqueethPoolTick current price tick for wsqueeth pool * @param _isWethToken0 whether weth is token0 in the wsqueeth pool * @return true if the vault is sufficiently collateralized * @return true if the vault is considered as a dust vault */ function getVaultStatus( Vault memory _vault, address _positionManager, uint256 _normalizationFactor, uint256 _ethQuoteCurrencyPrice, uint256 _minCollateral, int24 _wsqueethPoolTick, bool _isWethToken0 ) internal view returns (bool, bool) { if (_vault.shortAmount == 0) return (true, false); uint256 debtValueInETH = uint256(_vault.shortAmount).mul(_normalizationFactor).mul(_ethQuoteCurrencyPrice).div( ONE_ONE ); uint256 totalCollateral = _getEffectiveCollateral( _vault, _positionManager, _normalizationFactor, _ethQuoteCurrencyPrice, _wsqueethPoolTick, _isWethToken0 ); bool isDust = totalCollateral < _minCollateral; bool isAboveWater = totalCollateral.mul(CR_DENOMINATOR) >= debtValueInETH.mul(CR_NUMERATOR); return (isAboveWater, isDust); } /** * @notice get the total effective collateral of a vault, which is: * collateral amount + uniswap position token equivelent amount in eth * @param _vault the vault we want to check * @param _positionManager address of the uniswap position manager * @param _normalizationFactor current _normalizationFactor * @param _ethQuoteCurrencyPrice current eth price scaled by 1e18 * @param _wsqueethPoolTick current price tick for wsqueeth pool * @param _isWethToken0 whether weth is token0 in the wsqueeth pool * @return the total worth of collateral in the vault */ function _getEffectiveCollateral( Vault memory _vault, address _positionManager, uint256 _normalizationFactor, uint256 _ethQuoteCurrencyPrice, int24 _wsqueethPoolTick, bool _isWethToken0 ) internal view returns (uint256) { if (_vault.NftCollateralId == 0) return _vault.collateralAmount; // the user has deposited uniswap position token as collateral, see how much eth / wSqueeth the uniswap position token has (uint256 nftEthAmount, uint256 nftWsqueethAmount) = _getUniPositionBalances( _positionManager, _vault.NftCollateralId, _wsqueethPoolTick, _isWethToken0 ); // convert squeeth amount from uniswap position token as equivalent amount of collateral uint256 wSqueethIndexValueInEth = nftWsqueethAmount.mul(_normalizationFactor).mul(_ethQuoteCurrencyPrice).div( ONE_ONE ); // add eth value from uniswap position token as collateral return nftEthAmount.add(wSqueethIndexValueInEth).add(_vault.collateralAmount); } /** * @notice determine how much eth / wPowerPerp the uniswap position contains * @param _positionManager address of the uniswap position manager * @param _tokenId uniswap position token id * @param _wPowerPerpPoolTick current price tick * @param _isWethToken0 whether weth is token0 in the pool * @return ethAmount the eth amount this LP token contains * @return wPowerPerpAmount the wPowerPerp amount this LP token contains */ function _getUniPositionBalances( address _positionManager, uint256 _tokenId, int24 _wPowerPerpPoolTick, bool _isWethToken0 ) internal view returns (uint256 ethAmount, uint256 wPowerPerpAmount) { ( int24 tickLower, int24 tickUpper, uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) = _getUniswapPositionInfo(_positionManager, _tokenId); (uint256 amount0, uint256 amount1) = _getToken0Token1Balances( tickLower, tickUpper, _wPowerPerpPoolTick, liquidity ); return _isWethToken0 ? (amount0 + tokensOwed0, amount1 + tokensOwed1) : (amount1 + tokensOwed1, amount0 + tokensOwed0); } /** * @notice get uniswap position token info * @param _positionManager address of the uniswap position position manager * @param _tokenId uniswap position token id * @return tickLower lower tick of the position * @return tickUpper upper tick of the position * @return liquidity raw liquidity amount of the position * @return tokensOwed0 amount of token 0 can be collected as fee * @return tokensOwed1 amount of token 1 can be collected as fee */ function _getUniswapPositionInfo(address _positionManager, uint256 _tokenId) internal view returns ( int24, int24, uint128, uint128, uint128 ) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(_positionManager); ( , , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1 ) = positionManager.positions(_tokenId); return (tickLower, tickUpper, liquidity, tokensOwed0, tokensOwed1); } /** * @notice get balances of token0 / token1 in a uniswap position * @dev knowing liquidity, tick range, and current tick gives balances * @param _tickLower address of the uniswap position manager * @param _tickUpper uniswap position token id * @param _tick current price tick used for calculation * @return amount0 the amount of token0 in the uniswap position token * @return amount1 the amount of token1 in the uniswap position token */ function _getToken0Token1Balances( int24 _tickLower, int24 _tickUpper, int24 _tick, uint128 _liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { // get the current price and tick from wPowerPerp pool uint160 sqrtPriceX96 = TickMathExternal.getSqrtRatioAtTick(_tick); if (_tick < _tickLower) { amount0 = SqrtPriceMathPartial.getAmount0Delta( TickMathExternal.getSqrtRatioAtTick(_tickLower), TickMathExternal.getSqrtRatioAtTick(_tickUpper), _liquidity, true ); } else if (_tick < _tickUpper) { amount0 = SqrtPriceMathPartial.getAmount0Delta( sqrtPriceX96, TickMathExternal.getSqrtRatioAtTick(_tickUpper), _liquidity, true ); amount1 = SqrtPriceMathPartial.getAmount1Delta( TickMathExternal.getSqrtRatioAtTick(_tickLower), sqrtPriceX96, _liquidity, true ); } else { amount1 = SqrtPriceMathPartial.getAmount1Delta( TickMathExternal.getSqrtRatioAtTick(_tickLower), TickMathExternal.getSqrtRatioAtTick(_tickUpper), _liquidity, true ); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryPayments.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // 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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMathExternal { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) public pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), "T"); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) external pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R"); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@uniswap/v3-core/contracts/libraries/FullMath.sol"; import "@uniswap/v3-core/contracts/libraries/UnsafeMath.sol"; import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Exposes two functions from @uniswap/v3-core SqrtPriceMath /// that use square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMathPartial { /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) external pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) external pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } } //SPDX-License-Identifier: MIT pragma solidity =0.7.6; library Uint256Casting { /** * @notice cast a uint256 to a uint128, revert on overflow * @param y the uint256 to be downcasted * @return z the downcasted integer, now type uint128 */ function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y, "OF128"); } /** * @notice cast a uint256 to a uint96, revert on overflow * @param y the uint256 to be downcasted * @return z the downcasted integer, now type uint96 */ function toUint96(uint256 y) internal pure returns (uint96 z) { require((z = uint96(y)) == y, "OF96"); } /** * @notice cast a uint256 to a uint32, revert on overflow * @param y the uint256 to be downcasted * @return z the downcasted integer, now type uint32 */ function toUint32(uint256 y) internal pure returns (uint32 z) { require((z = uint32(y)) == y, "OF32"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Returns the number of pools in the path /// @param path The encoded swap path /// @return The number of pools in the path function numPools(bytes memory path) internal pure returns (uint256) { // Ignore the first token address. From then on every fee and token offset indicates a pool. return ((path.length - ADDR_SIZE) / NEXT_OFFSET); } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import './PoolAddress.sol'; /// @notice Provides validation for callbacks from Uniswap V3 Pools library CallbackValidation { /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The V3 pool contract address function verifyCallback( address factory, address tokenA, address tokenB, uint24 fee ) internal view returns (IUniswapV3Pool pool) { return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param poolKey The identifying key of the V3 pool /// @return pool The V3 pool contract address function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey) internal view returns (IUniswapV3Pool pool) { pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey)); require(msg.sender == address(pool)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } }
determine how much eth / wPowerPerp the uniswap position contains _positionManager address of the uniswap position manager _tokenId uniswap position token id _wPowerPerpPoolTick current price tick _isWethToken0 whether weth is token0 in the pool return ethAmount the eth amount this LP token contains return wPowerPerpAmount the wPowerPerp amount this LP token contains/
function _getUniPositionBalances( address _positionManager, uint256 _tokenId, int24 _wPowerPerpPoolTick, bool _isWethToken0 ) internal view returns (uint256 ethAmount, uint256 wPowerPerpAmount) { ( int24 tickLower, int24 tickUpper, uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) = _getUniswapPositionInfo(_positionManager, _tokenId); (uint256 amount0, uint256 amount1) = _getToken0Token1Balances( tickLower, tickUpper, _wPowerPerpPoolTick, liquidity ); return _isWethToken0 ? (amount0 + tokensOwed0, amount1 + tokensOwed1) : (amount1 + tokensOwed1, amount0 + tokensOwed0); }
1,220,225
./full_match/1/0x901b6D9Ef4D09d7Ad4AEb177F7F5c5BfaE868ccb/sources/browser/MultiverseMarket_1155dvi.sol
uint256 _oId = _orderId[_to][_itemCode];approve(_to, _order.itemId);
function Transaction_Item_WithToken(address _to, uint256 _oId, uint256 _amount, uint256 _price) external { address owner = address(uint160(orders[_oId].operator)); require(owner != msg.sender); require(owner != address(0)); Order storage _order = orders[_oId]; require(_price >= _order.price * _amount); require(_order.amount > 0); bool result = currencyToken.transferFrom(_to, owner, _price); require(result, "transfer token failed"); safeTransferFrom(owner, _to, _order.itemId, _amount, ""); _order.amount -= _amount; }
4,997,873
/** *Submitted for verification at Etherscan.io on 2021-09-28 */ /** *Submitted for verification at Etherscan.io on 2021-09-15 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //polygon plasma bridge interface IPlasmaBridge { event DepositERC20(address indexed depositor, address indexed depositReceiver, address indexed rootToken, uint256 amount); //matic deposits function depositERC20ForUser(address _token, address _user, uint256 _amount) external; } //polygon PoS bridge interface IPOSBridge { event DepositERC20(address indexed depositor, address indexed depositReceiver, address indexed rootToken, bytes amount); event DepositETH(address indexed depositor, address indexed depositReceiver, uint256 amount); //eth deposits function depositEtherFor(address user) external payable; //erc20 deposits function depositFor(address user, address rootToken, bytes calldata depositData) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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; } } } /** * @title Telcoin, LLC. * @dev Implements Openzeppelin Audited Contracts * * @notice this contract is meant for forwarding ERC20 and ETH accross the polygon bridge system. * This contract is meant to be a logic contract to work in conjunction with a proxy network. */ contract RootBridgeRelay is Initializable { event Relay(address indexed destination, address indexed currency, uint256 amount); // mainnet plasma bridge IPlasmaBridge constant public PLASMA_BRIDGE = IPlasmaBridge(0x401F6c983eA34274ec46f84D70b31C151321188b); // mainnet PoS bridge IPOSBridge constant public POS_BRIDGE = IPOSBridge(0xA0c68C638235ee32657e8f720a23ceC1bFc77C77); // mainnet predicate address constant public PREDICATE_ADDRESS = 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; //ETHER address address constant public ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //MATIC address address constant public MATIC_ADDRESS = 0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0; //max integer value uint256 constant public MAX_INT = 2**256 - 1; //polygon network receiving address address payable public recipient; /** * @notice initializes the contract its own address * @dev the recipient receives the same address as there will be a corresponding address on the adjoining network * @dev the reason for the use of the initialize function belonging to the initializable class * is to allow this contract to behave as the logic contract behind proxies. * @dev this function is called with proxy deployment to update state data * @dev uses initializer modifier to only allow one initialization per proxy */ function initialize() public initializer() { recipient = payable(address(this)); } /** * @notice pushes token transfers through to the appropriate bridge * @dev the contract is designed in a way where anyone can call the function without risking funds * @param token is address of the token that is desired to be pushed accross the bridge * @param amount is integer value of the quantity of the token * @return a boolean value indicating whether the operation succeeded. */ function bridgeTransfer(IERC20 token, uint256 amount) external payable returns (bool) { if (address(token) == ETHER_ADDRESS) { transferETHToBridge(amount); } else if (address(token) == MATIC_ADDRESS) { transferERCToPlasmaBridge(amount); } else { transferERCToBridge(token, amount); } return true; } /** * @notice pushes token transfers through to the PoS bridge * @dev this is for ERC20 tokens that are not the matic token * @dev only tokens that are already mapped on the bridge will succeed * @param token is address of the token that is desired to be pushed accross the bridge * @param amount is integer value of the quantity of the token */ function transferERCToBridge(IERC20 token, uint256 amount) internal { if (amount > token.allowance(recipient, PREDICATE_ADDRESS)) {approveERC20(token, PREDICATE_ADDRESS);} POS_BRIDGE.depositFor(recipient, address(token), abi.encodePacked(amount)); emit Relay(recipient, address(token), amount); } /** * @notice pushes matic token transfers through to the plasma bridge * @dev this is for the matic token * @param amount is integer value of the quantity of the matic token */ function transferERCToPlasmaBridge(uint256 amount) internal { if (amount > IERC20(MATIC_ADDRESS).allowance(recipient, address(PLASMA_BRIDGE))) {approveERC20(IERC20(MATIC_ADDRESS), address(PLASMA_BRIDGE));} PLASMA_BRIDGE.depositERC20ForUser(MATIC_ADDRESS, recipient, amount); emit Relay(recipient, MATIC_ADDRESS, amount); } /** * @notice pushes ETHER transfers through to the PoS bridge * @dev WETH will be minted to the recipient * @param amount is integer value of the quantity of ETH */ function transferETHToBridge(uint256 amount) internal { require(amount <= recipient.balance, "RootBridgeRelay: insufficient balance"); POS_BRIDGE.depositEtherFor{value: amount}(recipient); emit Relay(recipient, ETHER_ADDRESS, amount); } /** * @notice this approves any tokens for use by the bridge * @dev this function is called automatically when the allowance is not high enough for a particular token * @param token is address of the token needed to be approved * @param bridge is address of the token spender */ function approveERC20(IERC20 token, address bridge) internal { require(token.approve(bridge, MAX_INT), "RootBridgeRelay: Failed to approve tokens"); } /** * @notice receives ETHER */ receive() external payable {} }
pushes token transfers through to the appropriate bridge the contract is designed in a way where anyone can call the function without risking funds token is address of the token that is desired to be pushed accross the bridge amount is integer value of the quantity of the token return a boolean value indicating whether the operation succeeded./
function bridgeTransfer(IERC20 token, uint256 amount) external payable returns (bool) { if (address(token) == ETHER_ADDRESS) { transferETHToBridge(amount); transferERCToPlasmaBridge(amount); transferERCToBridge(token, amount); } return true; }
10,970,930
/** *Submitted for verification at Etherscan.io on 2021-07-28 */ /* https://powerpool.finance/ wrrrw r wrr ppwr rrr wppr0 prwwwrp prwwwrp wr0 rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0 rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0 r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0 prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0 wrr ww0rrrr */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <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: @powerpool/power-oracle/contracts/interfaces/IPowerPoke.sol pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface IPowerPoke { /*** CLIENT'S CONTRACT INTERFACE ***/ function authorizeReporter(uint256 userId_, address pokerKey_) external view; function authorizeNonReporter(uint256 userId_, address pokerKey_) external view; function authorizeNonReporterWithDeposit( uint256 userId_, address pokerKey_, uint256 overrideMinDeposit_ ) external view; function authorizePoker(uint256 userId_, address pokerKey_) external view; function authorizePokerWithDeposit( uint256 userId_, address pokerKey_, uint256 overrideMinStake_ ) external view; function slashReporter(uint256 slasherId_, uint256 times_) external; function reward( uint256 userId_, uint256 gasUsed_, uint256 compensationPlan_, bytes calldata pokeOptions_ ) external; /*** CLIENT OWNER INTERFACE ***/ function transferClientOwnership(address client_, address to_) external; function addCredit(address client_, uint256 amount_) external; function withdrawCredit( address client_, address to_, uint256 amount_ ) external; function setReportIntervals( address client_, uint256 minReportInterval_, uint256 maxReportInterval_ ) external; function setSlasherHeartbeat(address client_, uint256 slasherHeartbeat_) external; function setGasPriceLimit(address client_, uint256 gasPriceLimit_) external; function setFixedCompensations( address client_, uint256 eth_, uint256 cvp_ ) external; function setBonusPlan( address client_, uint256 planId_, bool active_, uint64 bonusNominator_, uint64 bonusDenominator_, uint64 perGas_ ) external; function setMinimalDeposit(address client_, uint256 defaultMinDeposit_) external; /*** POKER INTERFACE ***/ function withdrawRewards(uint256 userId_, address to_) external; function setPokerKeyRewardWithdrawAllowance(uint256 userId_, bool allow_) external; /*** OWNER INTERFACE ***/ function addClient( address client_, address owner_, bool canSlash_, uint256 gasPriceLimit_, uint256 minReportInterval_, uint256 maxReportInterval_ ) external; function setClientActiveFlag(address client_, bool active_) external; function setCanSlashFlag(address client_, bool canSlash) external; function setOracle(address oracle_) external; function pause() external; function unpause() external; /*** GETTERS ***/ function creditOf(address client_) external view returns (uint256); function ownerOf(address client_) external view returns (address); function getMinMaxReportIntervals(address client_) external view returns (uint256 min, uint256 max); function getSlasherHeartbeat(address client_) external view returns (uint256); function getGasPriceLimit(address client_) external view returns (uint256); function getPokerBonus( address client_, uint256 bonusPlanId_, uint256 gasUsed_, uint256 userDeposit_ ) external view returns (uint256); function getGasPriceFor(address client_) external view returns (uint256); } // File: contracts/interfaces/IUniswapV2Router01.sol pragma solidity 0.6.12; 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); } // File: contracts/interfaces/IUniswapV2Router02.sol pragma solidity 0.6.12; 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/interfaces/TokenInterface.sol pragma solidity 0.6.12; interface TokenInterface is IERC20 { function deposit() external payable; function withdraw(uint256) external; } // File: contracts/interfaces/BMathInterface.sol pragma solidity 0.6.12; interface BMathInterface { function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); } // File: contracts/interfaces/BPoolInterface.sol pragma solidity 0.6.12; interface BPoolInterface is IERC20, BMathInterface { function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external; function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external; function swapExactAmountIn( address, uint256, address, uint256, uint256 ) external returns (uint256, uint256); function swapExactAmountOut( address, uint256, address, uint256, uint256 ) external returns (uint256, uint256); function joinswapExternAmountIn( address, uint256, uint256 ) external returns (uint256); function joinswapPoolAmountOut( address, uint256, uint256 ) external returns (uint256); function exitswapPoolAmountIn( address, uint256, uint256 ) external returns (uint256); function exitswapExternAmountOut( address, uint256, uint256 ) external returns (uint256); function getDenormalizedWeight(address) external view returns (uint256); function getBalance(address) external view returns (uint256); function getSwapFee() external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getCommunityFee() external view returns ( uint256, uint256, uint256, address ); function calcAmountWithCommunityFee( uint256, uint256, address ) external view returns (uint256, uint256); function getRestrictions() external view returns (address); function isPublicSwap() external view returns (bool); function isFinalized() external view returns (bool); function isBound(address t) external view returns (bool); function getCurrentTokens() external view returns (address[] memory tokens); function getFinalTokens() external view returns (address[] memory tokens); function setSwapFee(uint256) external; function setCommunityFeeAndReceiver( uint256, uint256, uint256, address ) external; function setController(address) external; function setPublicSwap(bool) external; function finalize() external; function bind( address, uint256, uint256 ) external; function rebind( address, uint256, uint256 ) external; function unbind(address) external; function gulp(address) external; function callVoting( address voting, bytes4 signature, bytes calldata args, uint256 value ) external; function getMinWeight() external view returns (uint256); function getMaxBoundTokens() external view returns (uint256); } // File: contracts/interfaces/ICVPMakerStrategy.sol pragma solidity 0.6.12; interface ICVPMakerStrategy { function getExecuteDataByAmountOut( address poolTokenIn_, uint256 tokenOutAmount_, bytes memory config_ ) external view returns ( uint256 poolTokenInAmount, address executeUniLikeFrom, bytes memory executeData, address executeContract ); function getExecuteDataByAmountIn( address poolTokenIn_, uint256 tokenInAmount_, bytes memory config_ ) external view returns ( address executeUniLikeFrom, bytes memory executeData, address executeContract ); function estimateIn( address tokenIn_, uint256 tokenOutAmount_, bytes memory ) external view returns (uint256 amountIn); function estimateOut( address poolTokenIn_, uint256 tokenInAmount_, bytes memory ) external view returns (uint256); function getTokenOut() external view returns (address); } // File: contracts/balancer-core/BConst.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; contract BConst { uint public constant BONE = 10**18; // Minimum number of tokens in the pool uint public constant MIN_BOUND_TOKENS = 2; // Maximum number of tokens in the pool uint public constant MAX_BOUND_TOKENS = 9; // Minimum swap fee uint public constant MIN_FEE = BONE / 10**6; // Maximum swap fee uint public constant MAX_FEE = BONE / 10; // Minimum weight for token uint public constant MIN_WEIGHT = 1000000000; // Maximum weight for token uint public constant MAX_WEIGHT = BONE * 50; // Maximum total weight uint public constant MAX_TOTAL_WEIGHT = BONE * 50; // Minimum balance for a token uint public constant MIN_BALANCE = BONE / 10**12; // Initial pool tokens supply uint public constant INIT_POOL_SUPPLY = BONE * 100; uint public constant MIN_BPOW_BASE = 1 wei; uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint public constant BPOW_PRECISION = BONE / 10**10; // Maximum input tokens balance ratio for swaps. uint public constant MAX_IN_RATIO = BONE / 2; // Maximum output tokens balance ratio for swaps. uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; } // File: contracts/balancer-core/BNum.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; contract BNum is BConst { function btoi(uint a) internal pure returns (uint) { return a / BONE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BONE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / b; return c2; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "ERR_DIV_ZERO"); return a / b; } // DSMath.wpow function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { // term 0: uint a = exp; (uint x, bool xneg) = bsubSign(base, BONE); uint term = BONE; uint sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint i = 1; term >= precision; i++) { uint bigK = i * BONE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } // File: contracts/balancer-core/BMath.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; contract BMath is BConst, BNum, BMathInterface { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) public pure virtual returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure virtual returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure virtual override returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) public pure virtual returns (uint poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight | 1 - ---- | * sF // // sF = swapFee \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint poolAmountOut, uint swapFee ) public pure virtual override returns (uint tokenAmountIn) { uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint newPoolSupply = badd(poolSupply, poolAmountOut); uint poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint boo = bdiv(BONE, normalizedWeight); uint tokenInRatio = bpow(poolRatio, boo); uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint zar = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - pAi \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) public pure virtual returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); uint newPoolSupply = bsub(poolSupply, poolAmountIn); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight // // sF = swapFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee ) public pure virtual returns (uint poolAmountIn) { // charge swap fee on the output token side uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); //uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ; uint zoo = bsub(BONE, normalizedWeight); uint zar = bmul(zoo, swapFee); uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar)); uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee); uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint poolRatio = bpow(tokenOutRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); uint poolAmountIn = bsub(poolSupply, newPoolSupply); return poolAmountIn; } } // File: contracts/interfaces/WrappedPiErc20Interface.sol pragma solidity 0.6.12; interface WrappedPiErc20Interface is IERC20 { function deposit(uint256 _amount) external payable returns (uint256); function withdraw(uint256 _amount) external payable returns (uint256); function changeRouter(address _newRouter) external; function setEthFee(uint256 _newEthFee) external; function withdrawEthFee(address payable receiver) external; function approveUnderlying(address _to, uint256 _amount) external; function getPiEquivalentForUnderlying(uint256 _underlyingAmount) external view returns (uint256); function getUnderlyingEquivalentForPi(uint256 _piAmount) external view returns (uint256); function balanceOfUnderlying(address account) external view returns (uint256); function callExternal( address voting, bytes4 signature, bytes calldata args, uint256 value ) external; struct ExternalCallData { address destination; bytes4 signature; bytes args; uint256 value; } function callExternalMultiple(ExternalCallData[] calldata calls) external; function getUnderlyingBalance() external view returns (uint256); } // File: contracts/interfaces/PowerIndexWrapperInterface.sol pragma solidity 0.6.12; interface PowerIndexWrapperInterface { function getFinalTokens() external view returns (address[] memory tokens); function getCurrentTokens() external view returns (address[] memory tokens); function getBalance(address _token) external view returns (uint256); function setPiTokenForUnderlyingsMultiple(address[] calldata _underlyingTokens, address[] calldata _piTokens) external; function setPiTokenForUnderlying(address _underlyingTokens, address _piToken) external; function updatePiTokenEthFees(address[] calldata _underlyingTokens) external; function withdrawOddEthFee(address payable _recipient) external; function calcEthFeeForTokens(address[] memory tokens) external view returns (uint256 feeSum); function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external payable; function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external payable; function swapExactAmountIn( address, uint256, address, uint256, uint256 ) external payable returns (uint256, uint256); function swapExactAmountOut( address, uint256, address, uint256, uint256 ) external payable returns (uint256, uint256); function joinswapExternAmountIn( address, uint256, uint256 ) external payable returns (uint256); function joinswapPoolAmountOut( address, uint256, uint256 ) external payable returns (uint256); function exitswapPoolAmountIn( address, uint256, uint256 ) external payable returns (uint256); function exitswapExternAmountOut( address, uint256, uint256 ) external payable returns (uint256); } // File: contracts/lib/ControllerOwnable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an controller) that can be granted exclusive access to * specific functions. * * By default, the controller account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract ControllerOwnable { address private _controller; event SetController(address indexed previousController, address indexed newController); /** * @dev Initializes the contract setting the deployer as the initial controller. */ constructor () internal { _controller = msg.sender; emit SetController(address(0), _controller); } /** * @dev Returns the address of the current controller. */ function getController() public view returns (address) { return _controller; } /** * @dev Throws if called by any account other than the controller. */ modifier onlyController() { require(_controller == msg.sender, "NOT_CONTROLLER"); _; } /** * @dev Give the controller permissions to a new account (`newController`). * Can only be called by the current controller. */ function setController(address newController) public virtual onlyController { require(newController != address(0), "ControllerOwnable: new controller is the zero address"); emit SetController(_controller, newController); _controller = newController; } } // File: contracts/powerindex-router/PowerIndexWrapper.sol pragma solidity 0.6.12; contract PowerIndexWrapper is ControllerOwnable, BMath, PowerIndexWrapperInterface { using SafeMath for uint256; event SetPiTokenForUnderlying(address indexed underlyingToken, address indexed piToken); event UpdatePiTokenEthFee(address indexed piToken, uint256 ethFee); BPoolInterface public immutable bpool; mapping(address => address) public piTokenByUnderlying; mapping(address => address) public underlyingByPiToken; mapping(address => uint256) public ethFeeByPiToken; constructor(address _bpool) public ControllerOwnable() { bpool = BPoolInterface(_bpool); BPoolInterface(_bpool).approve(_bpool, uint256(-1)); address[] memory tokens = BPoolInterface(_bpool).getCurrentTokens(); uint256 len = tokens.length; for (uint256 i = 0; i < len; i++) { IERC20(tokens[i]).approve(_bpool, uint256(-1)); } } function withdrawOddEthFee(address payable _recipient) external override onlyController { _recipient.transfer(address(this).balance); } function setPiTokenForUnderlyingsMultiple(address[] calldata _underlyingTokens, address[] calldata _piTokens) external override onlyController { uint256 len = _underlyingTokens.length; require(len == _piTokens.length, "LENGTH_DONT_MATCH"); for (uint256 i = 0; i < len; i++) { _setPiTokenForUnderlying(_underlyingTokens[i], _piTokens[i]); } } function setPiTokenForUnderlying(address _underlyingToken, address _piToken) external override onlyController { _setPiTokenForUnderlying(_underlyingToken, _piToken); } function updatePiTokenEthFees(address[] calldata _underlyingTokens) external override { uint256 len = _underlyingTokens.length; for (uint256 i = 0; i < len; i++) { _updatePiTokenEthFee(piTokenByUnderlying[_underlyingTokens[i]]); } } function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external payable override returns (uint256 tokenAmountIn, uint256 spotPriceAfter) { (address actualTokenIn, uint256 actualMaxAmountIn) = _getActualTokenAndAmount(tokenIn, maxAmountIn); (address actualTokenOut, uint256 actualTokenAmountOut) = _getActualTokenAndAmount(tokenOut, tokenAmountOut); uint256 actualMaxPrice = getActualMaxPrice(maxAmountIn, actualMaxAmountIn, tokenAmountOut, actualTokenAmountOut, maxPrice); uint256 amountInRate = actualMaxAmountIn.mul(uint256(1 ether)).div(maxAmountIn); uint256 prevMaxAmount = actualMaxAmountIn; actualMaxAmountIn = calcInGivenOut( bpool.getBalance(actualTokenIn), bpool.getDenormalizedWeight(actualTokenIn), bpool.getBalance(actualTokenOut), bpool.getDenormalizedWeight(actualTokenOut), actualTokenAmountOut, bpool.getSwapFee() ); if (prevMaxAmount > actualMaxAmountIn) { maxAmountIn = actualMaxAmountIn.mul(uint256(1 ether)).div(amountInRate); } else { actualMaxAmountIn = prevMaxAmount; } _processUnderlyingTokenIn(tokenIn, maxAmountIn); (tokenAmountIn, spotPriceAfter) = bpool.swapExactAmountOut( actualTokenIn, actualMaxAmountIn, actualTokenOut, actualTokenAmountOut, actualMaxPrice ); _processUnderlyingOrPiTokenOutBalance(tokenOut); return (tokenAmountIn, spotPriceAfter); } function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external payable override returns (uint256 tokenAmountOut, uint256 spotPriceAfter) { (address actualTokenIn, uint256 actualAmountIn) = _processUnderlyingTokenIn(tokenIn, tokenAmountIn); (address actualTokenOut, uint256 actualMinAmountOut) = _getActualTokenAndAmount(tokenOut, minAmountOut); uint256 actualMaxPrice = getActualMaxPrice(tokenAmountIn, actualAmountIn, minAmountOut, actualMinAmountOut, maxPrice); (tokenAmountOut, spotPriceAfter) = bpool.swapExactAmountIn( actualTokenIn, actualAmountIn, actualTokenOut, actualMinAmountOut, actualMaxPrice ); _processUnderlyingOrPiTokenOutBalance(tokenOut); return (tokenAmountOut, spotPriceAfter); } function joinPool(uint256 poolAmountOut, uint256[] memory maxAmountsIn) external payable override { address[] memory tokens = getCurrentTokens(); uint256 len = tokens.length; require(maxAmountsIn.length == len, "ERR_LENGTH_MISMATCH"); uint256 ratio = poolAmountOut.mul(1 ether).div(bpool.totalSupply()).add(100); for (uint256 i = 0; i < len; i++) { (address actualToken, uint256 actualMaxAmountIn) = _getActualTokenAndAmount(tokens[i], maxAmountsIn[i]); uint256 amountInRate = actualMaxAmountIn.mul(uint256(1 ether)).div(maxAmountsIn[i]); uint256 prevMaxAmount = actualMaxAmountIn; actualMaxAmountIn = ratio.mul(bpool.getBalance(actualToken)).div(1 ether); if (prevMaxAmount > actualMaxAmountIn) { maxAmountsIn[i] = actualMaxAmountIn.mul(uint256(1 ether)).div(amountInRate); } else { actualMaxAmountIn = prevMaxAmount; } _processUnderlyingTokenIn(tokens[i], maxAmountsIn[i]); maxAmountsIn[i] = actualMaxAmountIn; } bpool.joinPool(poolAmountOut, maxAmountsIn); require(bpool.transfer(msg.sender, bpool.balanceOf(address(this))), "ERR_TRANSFER_FAILED"); } function exitPool(uint256 poolAmountIn, uint256[] memory minAmountsOut) external payable override { address[] memory tokens = getCurrentTokens(); uint256 len = tokens.length; require(minAmountsOut.length == len, "ERR_LENGTH_MISMATCH"); bpool.transferFrom(msg.sender, address(this), poolAmountIn); for (uint256 i = 0; i < len; i++) { (, minAmountsOut[i]) = _getActualTokenAndAmount(tokens[i], minAmountsOut[i]); } bpool.exitPool(poolAmountIn, minAmountsOut); for (uint256 i = 0; i < len; i++) { _processUnderlyingOrPiTokenOutBalance(tokens[i]); } } function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external payable override returns (uint256 poolAmountOut) { (address actualTokenIn, uint256 actualAmountIn) = _processUnderlyingTokenIn(tokenIn, tokenAmountIn); poolAmountOut = bpool.joinswapExternAmountIn(actualTokenIn, actualAmountIn, minPoolAmountOut); require(bpool.transfer(msg.sender, bpool.balanceOf(address(this))), "ERR_TRANSFER_FAILED"); return poolAmountOut; } function joinswapPoolAmountOut( address tokenIn, uint256 poolAmountOut, uint256 maxAmountIn ) external payable override returns (uint256 tokenAmountIn) { (address actualTokenIn, uint256 actualMaxAmountIn) = _getActualTokenAndAmount(tokenIn, maxAmountIn); uint256 amountInRate = actualMaxAmountIn.mul(uint256(1 ether)).div(maxAmountIn); uint256 prevMaxAmount = maxAmountIn; maxAmountIn = calcSingleInGivenPoolOut( getBalance(tokenIn), bpool.getDenormalizedWeight(actualTokenIn), bpool.totalSupply(), bpool.getTotalDenormalizedWeight(), poolAmountOut, bpool.getSwapFee() ); if (prevMaxAmount > maxAmountIn) { maxAmountIn = maxAmountIn; actualMaxAmountIn = maxAmountIn.mul(amountInRate).div(uint256(1 ether)); } else { maxAmountIn = prevMaxAmount; } _processUnderlyingTokenIn(tokenIn, maxAmountIn); tokenAmountIn = bpool.joinswapPoolAmountOut(actualTokenIn, poolAmountOut, actualMaxAmountIn); require(bpool.transfer(msg.sender, bpool.balanceOf(address(this))), "ERR_TRANSFER_FAILED"); return tokenAmountIn; } function exitswapPoolAmountIn( address tokenOut, uint256 poolAmountIn, uint256 minAmountOut ) external payable override returns (uint256 tokenAmountOut) { require(bpool.transferFrom(msg.sender, address(this), poolAmountIn), "ERR_TRANSFER_FAILED"); (address actualTokenOut, uint256 actualMinAmountOut) = _getActualTokenAndAmount(tokenOut, minAmountOut); tokenAmountOut = bpool.exitswapPoolAmountIn(actualTokenOut, poolAmountIn, actualMinAmountOut); _processUnderlyingOrPiTokenOutBalance(tokenOut); return tokenAmountOut; } function exitswapExternAmountOut( address tokenOut, uint256 tokenAmountOut, uint256 maxPoolAmountIn ) external payable override returns (uint256 poolAmountIn) { require(bpool.transferFrom(msg.sender, address(this), maxPoolAmountIn), "ERR_TRANSFER_FAILED"); (address actualTokenOut, uint256 actualTokenAmountOut) = _getActualTokenAndAmount(tokenOut, tokenAmountOut); poolAmountIn = bpool.exitswapExternAmountOut(actualTokenOut, actualTokenAmountOut, maxPoolAmountIn); _processUnderlyingOrPiTokenOutBalance(tokenOut); require(bpool.transfer(msg.sender, maxPoolAmountIn.sub(poolAmountIn)), "ERR_TRANSFER_FAILED"); return poolAmountIn; } function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) public pure override returns (uint256) { return super.calcInGivenOut(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, tokenAmountOut, swapFee).add( 1 ); } function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) public pure override returns (uint256) { return super .calcSingleInGivenPoolOut(tokenBalanceIn, tokenWeightIn, poolSupply, totalWeight, poolAmountOut, swapFee) .add(1); } function calcPoolInGivenSingleOut( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountOut, uint256 swapFee ) public pure override returns (uint256) { return super .calcPoolInGivenSingleOut(tokenBalanceOut, tokenWeightOut, poolSupply, totalWeight, tokenAmountOut, swapFee) .add(1); } function calcSpotPrice( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 swapFee ) public pure override returns (uint256) { return super.calcSpotPrice(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, swapFee).add(1); } function calcOutGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn, uint256 swapFee ) public pure override returns (uint256) { return super.calcOutGivenIn(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, tokenAmountIn, swapFee).sub( 10 ); } function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) public pure override returns (uint256) { return super .calcPoolOutGivenSingleIn(tokenBalanceIn, tokenWeightIn, poolSupply, totalWeight, tokenAmountIn, swapFee) .sub(10); } function calcSingleOutGivenPoolIn( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountIn, uint256 swapFee ) public pure override returns (uint256) { return super .calcSingleOutGivenPoolIn(tokenBalanceOut, tokenWeightOut, poolSupply, totalWeight, poolAmountIn, swapFee) .sub(10); } function getDenormalizedWeight(address token) external view returns (uint256) { return bpool.getDenormalizedWeight(_getActualToken(token)); } function getSwapFee() external view returns (uint256) { return bpool.getSwapFee(); } function calcEthFeeForTokens(address[] memory tokens) external view override returns (uint256 feeSum) { uint256 len = tokens.length; for (uint256 i = 0; i < len; i++) { address piToken = address(0); if (underlyingByPiToken[tokens[i]] != address(0)) { piToken = tokens[i]; } else if (piTokenByUnderlying[tokens[i]] != address(0)) { piToken = piTokenByUnderlying[tokens[i]]; } if (piToken != address(0)) { feeSum = feeSum.add(WrappedPiErc20EthFeeInterface(piToken).ethFee()); } } } function getCurrentTokens() public view override returns (address[] memory tokens) { tokens = bpool.getCurrentTokens(); uint256 len = tokens.length; for (uint256 i = 0; i < len; i++) { if (underlyingByPiToken[tokens[i]] != address(0)) { tokens[i] = underlyingByPiToken[tokens[i]]; } } } function getFinalTokens() public view override returns (address[] memory tokens) { return getCurrentTokens(); } function getBalance(address _token) public view override returns (uint256) { address piTokenAddress = piTokenByUnderlying[_token]; if (piTokenAddress == address(0)) { return bpool.getBalance(_token); } return WrappedPiErc20EthFeeInterface(piTokenAddress).getUnderlyingEquivalentForPi(bpool.getBalance(piTokenAddress)); } function getActualMaxPrice( uint256 amountIn, uint256 actualAmountIn, uint256 amountOut, uint256 actualAmountOut, uint256 maxPrice ) public returns (uint256 actualMaxPrice) { uint256 amountInRate = amountIn.mul(uint256(1 ether)).div(actualAmountIn); uint256 amountOutRate = actualAmountOut.mul(uint256(1 ether)).div(amountOut); return amountInRate > amountOutRate ? maxPrice.mul(amountInRate).div(amountOutRate) : maxPrice.mul(amountOutRate).div(amountInRate); } function _processUnderlyingTokenIn(address _underlyingToken, uint256 _amount) internal returns (address actualToken, uint256 actualAmount) { if (_amount == 0) { return (_underlyingToken, _amount); } require(IERC20(_underlyingToken).transferFrom(msg.sender, address(this), _amount), "ERR_TRANSFER_FAILED"); actualToken = piTokenByUnderlying[_underlyingToken]; if (actualToken == address(0)) { return (_underlyingToken, _amount); } actualAmount = WrappedPiErc20Interface(actualToken).deposit{ value: ethFeeByPiToken[actualToken] }(_amount); } function _processPiTokenOutBalance(address _piToken) internal { uint256 balance = WrappedPiErc20EthFeeInterface(_piToken).balanceOfUnderlying(address(this)); WrappedPiErc20Interface(_piToken).withdraw{ value: ethFeeByPiToken[_piToken] }(balance); require(IERC20(underlyingByPiToken[_piToken]).transfer(msg.sender, balance), "ERR_TRANSFER_FAILED"); } function _processUnderlyingTokenOutBalance(address _underlyingToken) internal returns (uint256 balance) { balance = IERC20(_underlyingToken).balanceOf(address(this)); require(IERC20(_underlyingToken).transfer(msg.sender, balance), "ERR_TRANSFER_FAILED"); } function _processUnderlyingOrPiTokenOutBalance(address _underlyingOrPiToken) internal { address piToken = piTokenByUnderlying[_underlyingOrPiToken]; if (piToken == address(0)) { _processUnderlyingTokenOutBalance(_underlyingOrPiToken); } else { _processPiTokenOutBalance(piToken); } } function _getActualToken(address token) internal view returns (address) { address piToken = piTokenByUnderlying[token]; return piToken == address(0) ? token : piToken; } function _getActualTokenAndAmount(address token, uint256 amount) internal view returns (address actualToken, uint256 actualAmount) { address piToken = piTokenByUnderlying[token]; if (piToken == address(0)) { return (token, amount); } return (piToken, WrappedPiErc20EthFeeInterface(piToken).getPiEquivalentForUnderlying(amount)); } function _setPiTokenForUnderlying(address underlyingToken, address piToken) internal { piTokenByUnderlying[underlyingToken] = piToken; if (piToken == address(0)) { IERC20(underlyingToken).approve(address(bpool), uint256(-1)); } else { underlyingByPiToken[piToken] = underlyingToken; IERC20(piToken).approve(address(bpool), uint256(-1)); IERC20(underlyingToken).approve(piToken, uint256(-1)); _updatePiTokenEthFee(piToken); } emit SetPiTokenForUnderlying(underlyingToken, piToken); } function _updatePiTokenEthFee(address piToken) internal { if (piToken == address(0)) { return; } uint256 ethFee = WrappedPiErc20EthFeeInterface(piToken).ethFee(); if (ethFeeByPiToken[piToken] == ethFee) { return; } ethFeeByPiToken[piToken] = ethFee; emit UpdatePiTokenEthFee(piToken, ethFee); } } interface WrappedPiErc20EthFeeInterface { function ethFee() external view returns (uint256); function router() external view returns (address); function getPiEquivalentForUnderlying(uint256 _underlyingAmount) external view returns (uint256); function getUnderlyingEquivalentForPi(uint256 _piAmount) external view returns (uint256); function balanceOfUnderlying(address _account) external view returns (uint256); } // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 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: contracts/interfaces/IPoolRestrictions.sol pragma solidity 0.6.12; interface IPoolRestrictions { function getMaxTotalSupply(address _pool) external view returns (uint256); function isVotingSignatureAllowed(address _votingAddress, bytes4 _signature) external view returns (bool); function isVotingSenderAllowed(address _votingAddress, address _sender) external view returns (bool); function isWithoutFee(address _addr) external view returns (bool); } // File: contracts/pvp/CVPMakerStorage.sol pragma solidity 0.6.12; contract CVPMakerStorage is OwnableUpgradeSafe { IPowerPoke public powerPoke; uint256 public cvpAmountOut; uint256 public lastReporterPokeFrom; IPoolRestrictions public restrictions; // token => router mapping(address => address) public routers; // token => [path, to, cvp] mapping(address => address[]) public customPaths; // token => strategyId mapping(address => uint256) public customStrategies; struct ExternalStrategiesConfig { address strategy; bool maxAmountIn; bytes config; } // token => strategyAddress mapping(address => ExternalStrategiesConfig) public externalStrategiesConfig; struct Strategy1Config { address bPoolWrapper; } struct Strategy2Config { address bPoolWrapper; uint256 nextIndex; address[] tokens; } struct Strategy3Config { address bPool; address bPoolWrapper; address underlying; } mapping(address => Strategy1Config) public strategy1Config; mapping(address => Strategy2Config) public strategy2Config; mapping(address => Strategy3Config) public strategy3Config; } // File: contracts/interfaces/ICVPMakerViewer.sol pragma solidity 0.6.12; interface ICVPMakerViewer { function getRouter(address token_) external view returns (address); function getPath(address token_) external view returns (address[] memory); function getDefaultPath(address token_) external view returns (address[] memory); /*** ESTIMATIONS ***/ function estimateEthStrategyIn() external view returns (uint256); function estimateEthStrategyOut(address tokenIn_, uint256 _amountIn) external view returns (uint256); function estimateUniLikeStrategyIn(address token_) external view returns (uint256); function estimateUniLikeStrategyOut(address token_, uint256 amountIn_) external view returns (uint256); /*** CUSTOM STRATEGIES OUT ***/ function calcBPoolGrossAmount(uint256 tokenAmountNet_, uint256 communityFee_) external view returns (uint256 tokenAmountGross); } // File: contracts/pvp/CVPMakerViewer.sol pragma solidity 0.6.12; contract CVPMakerViewer is ICVPMakerViewer, CVPMakerStorage { using SafeMath for uint256; address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 public constant COMPENSATION_PLAN_1_ID = 1; uint256 public constant BONE = 10**18; // 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D address public immutable uniswapRouter; // 0x38e4adb44ef08f22f5b5b76a8f0c2d0dcbe7dca1 address public immutable cvp; // 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 address public immutable weth; address public immutable xcvp; constructor( address cvp_, address xcvp_, address weth_, address uniswapRouter_ ) public { cvp = cvp_; xcvp = xcvp_; weth = weth_; uniswapRouter = uniswapRouter_; } function wethCVPPath() public view returns (address[] memory) { address[] memory path = new address[](2); path[0] = weth; path[1] = cvp; return path; } function _wethTokenPath(address _token) internal view returns (address[] memory) { address[] memory path = new address[](2); path[0] = _token; path[1] = weth; return path; } function getRouter(address token_) public view override returns (address) { address router = routers[token_]; if (router == address(0)) { return uniswapRouter; } return router; } function getPath(address token_) public view override returns (address[] memory) { address[] storage customPath = customPaths[token_]; if (customPath.length == 0) { return getDefaultPath(token_); } return customPath; } function getDefaultPath(address token_) public view override returns (address[] memory) { address[] memory path = new address[](3); path[0] = token_; path[1] = weth; path[2] = cvp; return path; } function getStrategy1Config(address token_) external view returns (address bPoolWrapper) { Strategy1Config memory strategy = strategy1Config[token_]; return (strategy.bPoolWrapper); } function getStrategy2Config(address token_) external view returns (address bPoolWrapper, uint256 nextIndex) { Strategy2Config storage strategy = strategy2Config[token_]; return (strategy.bPoolWrapper, strategy.nextIndex); } function getStrategy2Tokens(address token_) external view returns (address[] memory) { return strategy2Config[token_].tokens; } function getStrategy3Config(address token_) external view returns ( address bPool, address bPoolWrapper, address underlying ) { Strategy3Config storage strategy = strategy3Config[token_]; return (strategy.bPool, strategy.bPoolWrapper, strategy.underlying); } function getExternalStrategyConfig(address token_) external view returns ( address strategy, bool maxAmountIn, bytes memory config ) { ExternalStrategiesConfig memory strategy = externalStrategiesConfig[token_]; return (strategy.strategy, strategy.maxAmountIn, strategy.config); } function getCustomPaths(address token_) public view returns (address[] memory) { return customPaths[token_]; } /*** ESTIMATIONS ***/ function estimateEthStrategyIn() public view override returns (uint256) { uint256[] memory results = IUniswapV2Router02(uniswapRouter).getAmountsIn(cvpAmountOut, wethCVPPath()); return results[0]; } function estimateEthStrategyOut(address tokenIn_, uint256 _amountIn) public view override returns (uint256) { uint256[] memory results = IUniswapV2Router02(uniswapRouter).getAmountsOut(_amountIn, _wethTokenPath(tokenIn_)); return results[0]; } /** * @notice Estimates how much token_ need to swap for cvpAmountOut * @param token_ The token to swap for CVP * @return The estimated token_ amount in */ function estimateUniLikeStrategyIn(address token_) public view override returns (uint256) { address router = getRouter(token_); address[] memory path = getPath(token_); if (router == uniswapRouter) { uint256[] memory results = IUniswapV2Router02(router).getAmountsIn(cvpAmountOut, path); return results[0]; } else { uint256 wethToSwap = estimateEthStrategyIn(); uint256[] memory results = IUniswapV2Router02(router).getAmountsIn(wethToSwap, path); return results[0]; } } function estimateUniLikeStrategyOut(address token_, uint256 amountIn_) public view override returns (uint256) { address router = getRouter(token_); address[] memory path = getPath(token_); if (router == uniswapRouter) { uint256[] memory results = IUniswapV2Router02(router).getAmountsOut(amountIn_, path); return results[2]; } else { uint256 wethToSwap = estimateEthStrategyOut(token_, amountIn_); uint256[] memory results = IUniswapV2Router02(router).getAmountsOut(wethToSwap, path); return results[2]; } } /*** CUSTOM STRATEGIES OUT ***/ /** * @notice Calculates the gross amount based on a net and a fee values. The function is opposite to * the BPool.calcAmountWithCommunityFee(). */ function calcBPoolGrossAmount(uint256 tokenAmountNet_, uint256 communityFee_) public view override returns (uint256 tokenAmountGross) { if (address(restrictions) != address(0) && restrictions.isWithoutFee(address(this))) { return (tokenAmountNet_); } uint256 adjustedIn = bsub(BONE, communityFee_); return bdiv(tokenAmountNet_, adjustedIn); } function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / b; return c2; } } // File: contracts/pvp/CVPMaker.sol pragma solidity 0.6.12; contract CVPMaker is OwnableUpgradeSafe, CVPMakerStorage, CVPMakerViewer { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice The event emitted when the owner updates the powerOracleStaking address event SetPowerPoke(address powerPoke); /// @notice The event emitted when a poker calls swapFromReporter to convert token to CVP event Swap( address indexed caller, address indexed token, SwapType indexed swapType, uint256 amountIn, uint256 amountOut, uint256 xcvpCvpBefore, uint256 xcvpCvpAfter ); /// @notice The event emitted when the owner updates cvpAmountOut value event SetPoolRestrictions(address poolRestrictions); /// @notice The event emitted when the owner updates cvpAmountOut value event SetCvpAmountOut(uint256 cvpAmountOut); /// @notice The event emitted when the owner updates a token custom uni-like path event SetCustomPath(address indexed token_, address router_, address[] path); /// @notice The event emitted when the owner assigns a custom strategy for the token event SetCustomStrategy(address indexed token, uint256 strategyId); /// @notice The event emitted when the owner configures an external strategy for the token event SetExternalStrategy(address indexed token_, address indexed strategy, bool maxAmountIn); enum SwapType { NULL, CVP, ETH, CUSTOM_STRATEGY, EXTERNAL_STRATEGY, UNI_LIKE_STRATEGY } modifier onlyEOA() { require(msg.sender == tx.origin, "NOT_EOA"); _; } modifier onlyReporter(uint256 reporterId_, bytes calldata rewardOpts_) { uint256 gasStart = gasleft(); powerPoke.authorizeReporter(reporterId_, msg.sender); _; powerPoke.reward(reporterId_, gasStart.sub(gasleft()), COMPENSATION_PLAN_1_ID, rewardOpts_); } modifier onlySlasher(uint256 slasherId_, bytes calldata rewardOpts_) { uint256 gasStart = gasleft(); powerPoke.authorizeNonReporter(slasherId_, msg.sender); _; powerPoke.reward(slasherId_, gasStart.sub(gasleft()), COMPENSATION_PLAN_1_ID, rewardOpts_); } constructor( address cvp_, address xcvp_, address weth_, address uniswapRouter_ ) public CVPMakerViewer(cvp_, xcvp_, weth_, uniswapRouter_) {} receive() external payable {} function initialize( address powerPoke_, address restrictions_, uint256 cvpAmountOut_ ) external initializer { require(cvpAmountOut_ > 0, "CVP_AMOUNT_OUT_0"); powerPoke = IPowerPoke(powerPoke_); restrictions = IPoolRestrictions(restrictions_); cvpAmountOut = cvpAmountOut_; emit SetPowerPoke(powerPoke_); emit SetCvpAmountOut(cvpAmountOut_); __Ownable_init(); } /** * @notice The swap call from the reporter * @param reporterId_ The current reporter id * @param token_ The token to swap to CVP * @param rewardOpts_ Custom settings for the reporter reward */ function swapFromReporter( uint256 reporterId_, address token_, bytes calldata rewardOpts_ ) external onlyEOA onlyReporter(reporterId_, rewardOpts_) { (uint256 minInterval, ) = _getMinMaxReportInterval(); require(block.timestamp.sub(lastReporterPokeFrom) > minInterval, "MIN_INTERVAL_NOT_REACHED"); _swap(token_); } /** * @notice The swap call from a slasher in case if the reporter has missed his call * @param slasherId_ The current slasher id * @param token_ The token to swap to CVP * @param rewardOpts_ Custom settings for the slasher reward */ function swapFromSlasher( uint256 slasherId_, address token_, bytes calldata rewardOpts_ ) external onlyEOA onlySlasher(slasherId_, rewardOpts_) { (, uint256 maxInterval) = _getMinMaxReportInterval(); require(block.timestamp.sub(lastReporterPokeFrom) > maxInterval, "MAX_INTERVAL_NOT_REACHED"); _swap(token_); } /*** SWAP HELPERS ***/ function _getMinMaxReportInterval() internal view returns (uint256 min, uint256 max) { return powerPoke.getMinMaxReportIntervals(address(this)); } function _swap(address token_) internal { uint256 cvpBefore = IERC20(cvp).balanceOf(xcvp); lastReporterPokeFrom = block.timestamp; uint256 cvpAmountOut_ = cvpAmountOut; SwapType sType; uint256 amountIn = 0; // Just transfer CVPs to xCVP contract if (token_ == cvp) { sType = SwapType.CVP; amountIn = IERC20(cvp).balanceOf(address(this)); IERC20(cvp).safeTransfer(xcvp, amountIn); cvpAmountOut_ = amountIn; } else if (token_ == weth || token_ == ETH) { // Wrap ETH -> WETH if (token_ == ETH) { amountIn = address(this).balance; require(amountIn > 0, "ETH_BALANCE_IS_0"); TokenInterface(weth).deposit{ value: amountIn }(); } // Use a single pair path to swap WETH -> CVP amountIn = _swapWETHToCVP(); sType = SwapType.ETH; } else { uint256 customStrategyId = customStrategies[token_]; if (customStrategyId > 0) { amountIn = _executeCustomStrategy(token_, customStrategyId); sType = SwapType.CUSTOM_STRATEGY; } else if (externalStrategiesConfig[token_].strategy != address(0)) { amountIn = _executeExternalStrategy(token_); sType = SwapType.EXTERNAL_STRATEGY; } else { // Use a Uniswap-like strategy amountIn = _executeUniLikeStrategy(token_); sType = SwapType.UNI_LIKE_STRATEGY; } } uint256 cvpAfter = IERC20(cvp).balanceOf(xcvp); if (sType != SwapType.EXTERNAL_STRATEGY) { require(cvpAfter.sub(cvpBefore) >= (cvpAmountOut * 99) / 100, "LESS_THAN_CVP_AMOUNT_OUT"); } emit Swap(msg.sender, token_, sType, amountIn, cvpAmountOut_, cvpBefore, cvpAfter); } function _executeUniLikeStrategy(address token_) internal returns (uint256 amountOut) { address router = getRouter(token_); address[] memory path = getPath(token_); if (router == uniswapRouter) { amountOut = _swapTokensForExactCVP(router, token_, path); } else { uint256 wethAmountIn = estimateEthStrategyIn(); amountOut = _swapTokensForExactWETH(router, token_, path, wethAmountIn); _swapWETHToCVP(); } } function _swapTokensForExactWETH( address router_, address token_, address[] memory path_, uint256 amountOut_ ) internal returns (uint256 amountIn) { IERC20(token_).approve(router_, type(uint256).max); uint256[] memory amounts = IUniswapV2Router02(router_).swapTokensForExactTokens( amountOut_, type(uint256).max, path_, address(this), block.timestamp ); IERC20(token_).approve(router_, 0); return amounts[0]; } function _swapWETHToCVP() internal returns (uint256) { address[] memory path = new address[](2); path[0] = weth; path[1] = cvp; IERC20(weth).approve(uniswapRouter, type(uint256).max); uint256[] memory amounts = IUniswapV2Router02(uniswapRouter).swapTokensForExactTokens( cvpAmountOut, type(uint256).max, path, xcvp, block.timestamp ); IERC20(weth).approve(uniswapRouter, 0); return amounts[0]; } function _swapTokensForExactCVP( address router_, address token_, address[] memory path_ ) internal returns (uint256) { IERC20(token_).approve(router_, type(uint256).max); uint256[] memory amounts = IUniswapV2Router02(router_).swapTokensForExactTokens( cvpAmountOut, type(uint256).max, path_, xcvp, block.timestamp ); IERC20(token_).approve(router_, 0); return amounts[0]; } function _executeExternalStrategy(address token_) internal returns (uint256 amountIn) { ExternalStrategiesConfig memory config = externalStrategiesConfig[token_]; address executeUniLikeFrom; address executeContract; bytes memory executeData; if (config.maxAmountIn) { amountIn = IERC20(token_).balanceOf(address(this)); uint256 strategyAmountOut = ICVPMakerStrategy(config.strategy).estimateOut(token_, amountIn, config.config); uint256 resultCvpOut = estimateUniLikeStrategyOut(ICVPMakerStrategy(config.strategy).getTokenOut(), strategyAmountOut); require(resultCvpOut >= cvpAmountOut, "INSUFFICIENT_CVP_AMOUNT_OUT"); (executeUniLikeFrom, executeData, executeContract) = ICVPMakerStrategy(config.strategy).getExecuteDataByAmountIn( token_, amountIn, config.config ); } else { (amountIn, executeUniLikeFrom, executeData, executeContract) = ICVPMakerStrategy(config.strategy) .getExecuteDataByAmountOut( token_, estimateUniLikeStrategyIn(ICVPMakerStrategy(config.strategy).getTokenOut()), config.config ); } IERC20(token_).approve(executeContract, amountIn); (bool success, bytes memory data) = executeContract.call(executeData); require(success, "NOT_SUCCESS"); if (executeUniLikeFrom != address(0)) { _executeUniLikeStrategy(executeUniLikeFrom); } } function _executeCustomStrategy(address token_, uint256 strategyId_) internal returns (uint256 amountIn) { if (strategyId_ == 1) { return _customStrategy1(token_); } else if (strategyId_ == 2) { return _customStrategy2(token_); } else if (strategyId_ == 3) { return _customStrategy3(token_); } else { revert("INVALID_STRATEGY_ID"); } } /*** CUSTOM STRATEGIES ***/ /** * @notice The Strategy 1 exits a PowerIndex pool to CVP token. The pool should have CVP token bound. * (For PIPT & YETI - like pools) * @param bPoolToken_ PowerIndex Pool Token * @return amountIn The amount of bPoolToken_ used as an input for the swap */ function _customStrategy1(address bPoolToken_) internal returns (uint256 amountIn) { uint256 cvpAmountOut_ = cvpAmountOut; Strategy1Config memory config = strategy1Config[bPoolToken_]; address iBPool = bPoolToken_; if (config.bPoolWrapper != address(0)) { iBPool = config.bPoolWrapper; } (, , uint256 communityExitFee, ) = BPoolInterface(bPoolToken_).getCommunityFee(); uint256 amountOutGross = calcBPoolGrossAmount(cvpAmountOut_, communityExitFee); uint256 currentBalance = IERC20(bPoolToken_).balanceOf(address(this)); IERC20(bPoolToken_).approve(iBPool, currentBalance); amountIn = BPoolInterface(iBPool).exitswapExternAmountOut(cvp, amountOutGross, currentBalance); IERC20(bPoolToken_).approve(iBPool, 0); IERC20(cvp).safeTransfer(xcvp, cvpAmountOut_); } /** * @notice The Strategy 2 exits from a PowerIndex pool token to one of it's bound tokens. Then it swaps this token * for CVP using a uniswap-like strategy. The pool should have CVP token bound. (For ASSY - like pools) * @param bPoolToken_ PowerIndex Pool Token * @return amountIn The amount of bPoolToken_ used as an input for the swap */ function _customStrategy2(address bPoolToken_) internal returns (uint256 amountIn) { Strategy2Config storage config = strategy2Config[bPoolToken_]; uint256 nextIndex = config.nextIndex; address underlyingOrPiToExit = config.tokens[nextIndex]; require(underlyingOrPiToExit != address(0), "INVALID_EXIT_TOKEN"); address underlyingToken = underlyingOrPiToExit; if (nextIndex + 1 >= config.tokens.length) { config.nextIndex = 0; } else { config.nextIndex = nextIndex + 1; } address iBPool = bPoolToken_; if (config.bPoolWrapper != address(0)) { iBPool = config.bPoolWrapper; address underlyingCandidate = PowerIndexWrapper(config.bPoolWrapper).underlyingByPiToken(underlyingOrPiToExit); if (underlyingCandidate != address(0)) { underlyingToken = underlyingCandidate; } } uint256 tokenAmountUniIn = estimateUniLikeStrategyIn(underlyingToken); (, , uint256 communityExitFee, ) = BPoolInterface(bPoolToken_).getCommunityFee(); uint256 amountOutGross = calcBPoolGrossAmount(tokenAmountUniIn, communityExitFee); uint256 currentBalance = IERC20(bPoolToken_).balanceOf(address(this)); IERC20(bPoolToken_).approve(iBPool, currentBalance); amountIn = BPoolInterface(iBPool).exitswapExternAmountOut(underlyingToken, amountOutGross, currentBalance); IERC20(bPoolToken_).approve(iBPool, 0); _executeUniLikeStrategy(underlyingToken); } /** * @notice The Strategy 3 swaps the given token at the corresponding PowerIndex pool for CVP * @param underlyingOrPiToken_ Token to swap for CVP. If it is a piToken, all the balance is swapped for it's * underlying first. * @return amountIn The amount used as an input for the swap. For a piToken it returns the amount in underlying tokens */ function _customStrategy3(address underlyingOrPiToken_) internal returns (uint256 amountIn) { Strategy3Config memory config = strategy3Config[underlyingOrPiToken_]; BPoolInterface bPool = BPoolInterface(config.bPool); BPoolInterface bPoolWrapper = config.bPoolWrapper != address(0) ? BPoolInterface(config.bPoolWrapper) : bPool; address tokenIn = underlyingOrPiToken_; if (config.underlying != address(0)) { tokenIn = config.underlying; uint256 underlyingBalance = WrappedPiErc20Interface(underlyingOrPiToken_).balanceOfUnderlying(address(this)); if (underlyingBalance > 0) { WrappedPiErc20Interface(underlyingOrPiToken_).withdraw(underlyingBalance); } } (uint256 communitySwapFee, , , ) = bPool.getCommunityFee(); uint256 cvpAmountOut_ = cvpAmountOut; uint256 amountOutGross = calcBPoolGrossAmount(cvpAmountOut_, communitySwapFee); uint256 currentBalance = IERC20(tokenIn).balanceOf(address(this)); IERC20(tokenIn).approve(address(bPoolWrapper), currentBalance); (amountIn, ) = bPoolWrapper.swapExactAmountOut( // tokenIn tokenIn, // maxAmountIn currentBalance, // tokenOut cvp, // tokenAmountOut amountOutGross, // maxPrice type(uint64).max ); IERC20(tokenIn).approve(address(bPoolWrapper), 0); IERC20(cvp).safeTransfer(xcvp, cvpAmountOut_); } /*** PERMISSIONLESS METHODS ***/ /** * @notice Syncs the bound tokens for the Strategy2 PowerIndex pool token * @param token_ The pool token to sync */ function syncStrategy2Tokens(address token_) external { require(customStrategies[token_] == 2, "CUSTOM_STRATEGY_2_FORBIDDEN"); Strategy2Config storage config = strategy2Config[token_]; address[] memory newTokens = BPoolInterface(token_).getCurrentTokens(); require(newTokens.length > 0, "NEW_LENGTH_IS_0"); config.tokens = newTokens; if (config.nextIndex >= newTokens.length) { config.nextIndex = 0; } } /*** OWNER METHODS ***/ function setPoolRestrictions(address restrictions_) external onlyOwner { restrictions = IPoolRestrictions(restrictions_); emit SetPoolRestrictions(restrictions_); } function setCvpAmountOut(uint256 cvpAmountOut_) external onlyOwner { require(cvpAmountOut_ > 0, "CVP_AMOUNT_OUT_0"); cvpAmountOut = cvpAmountOut_; emit SetCvpAmountOut(cvpAmountOut_); } function setCustomStrategy(address token_, uint256 strategyId_) public onlyOwner { customStrategies[token_] = strategyId_; emit SetCustomStrategy(token_, strategyId_); } function setCustomStrategy1Config(address bPoolToken_, address bPoolWrapper_) external onlyOwner { strategy1Config[bPoolToken_].bPoolWrapper = bPoolWrapper_; setCustomStrategy(bPoolToken_, 1); } function setCustomStrategy2Config(address bPoolToken, address bPoolWrapper_) external onlyOwner { strategy2Config[bPoolToken].bPoolWrapper = bPoolWrapper_; setCustomStrategy(bPoolToken, 2); } function setCustomStrategy3Config( address token_, address bPool_, address bPoolWrapper_, address underlying_ ) external onlyOwner { strategy3Config[token_] = Strategy3Config(bPool_, bPoolWrapper_, underlying_); setCustomStrategy(token_, 3); } function setExternalStrategy( address token_, address strategy_, bool maxAmountIn_, bytes memory config_ ) external onlyOwner { address prevStrategy = externalStrategiesConfig[token_].strategy; if (prevStrategy != address(0)) { IERC20(token_).safeApprove(prevStrategy, uint256(0)); } externalStrategiesConfig[token_] = ExternalStrategiesConfig(strategy_, maxAmountIn_, config_); IERC20(token_).safeApprove(strategy_, type(uint256).max); emit SetExternalStrategy(token_, strategy_, maxAmountIn_); } function setCustomPath( address token_, address router_, address[] calldata customPath_ ) external onlyOwner { if (router_ == uniswapRouter) { require(customPath_.length == 0 || customPath_[customPath_.length - 1] == cvp, "NON_CVP_END_ON_UNISWAP_PATH"); } else { require(customPath_[customPath_.length - 1] == weth, "NON_WETH_END_ON_NON_UNISWAP_PATH"); } routers[token_] = router_; customPaths[token_] = customPath_; emit SetCustomPath(token_, router_, customPath_); } }
Syncs the bound tokens for the Strategy2 PowerIndex pool token token_ The pool token to sync/
function syncStrategy2Tokens(address token_) external { require(customStrategies[token_] == 2, "CUSTOM_STRATEGY_2_FORBIDDEN"); Strategy2Config storage config = strategy2Config[token_]; address[] memory newTokens = BPoolInterface(token_).getCurrentTokens(); require(newTokens.length > 0, "NEW_LENGTH_IS_0"); config.tokens = newTokens; if (config.nextIndex >= newTokens.length) { config.nextIndex = 0; } }
8,038,693
./full_match/1/0x518eDc741A94B217F07583cDDDEb0266c33DD04D/sources/browser/TorroMigrate.sol
Migrates balances of current DAO to a new DAO. newDao_ address of the new DAO to migrate to. Migrate holdings.
function migrate(address newDao_) public override onlyOwner { ITorroDao dao = ITorroDao(newDao_); address[] memory currentHoldings = holdings(); for (uint256 i = 0; i < currentHoldings.length; i++) { _migrateTransferBalance(currentHoldings[i], newDao_); } dao.addHoldingsAddresses(currentHoldings); for (uint256 i = 0; i < currentLiquidities.length; i++) { _migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_); } dao.addLiquidityAddresses(currentLiquidities); }
17,041,459
./full_match/421611/0x481148ed881807B574548B759141A0F515060d3f/sources/_aave/core-v3/contracts/protocol/libraries/logic/BorrowLogic.sol
since the debt ceiling does not take into account the interest accrued, it might happen that amount repaid > debt in isolation mode
function executeRepay( mapping(address => DataTypes.ReserveData) storage reserves, mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ExecuteRepayParams memory params ) external returns (uint256) { DataTypes.ReserveCache memory reserveCache = reserve.cache(); (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt( params.onBehalfOf, reserve ); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(params.rateMode); reserve.updateState(reserveCache); ValidationLogic.validateRepay( reserveCache, params.amount, interestRateMode, params.onBehalfOf, stableDebt, variableDebt ); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (params.amount < paybackAmount) { paybackAmount = params.amount; } if (interestRateMode == DataTypes.InterestRateMode.STABLE) { (reserveCache.nextTotalStableDebt, reserveCache.nextAvgStableBorrowRate) = IStableDebtToken( reserveCache.stableDebtTokenAddress ).burn(params.onBehalfOf, paybackAmount); reserveCache.nextScaledVariableDebt = IVariableDebtToken( reserveCache.variableDebtTokenAddress ).burn(params.onBehalfOf, paybackAmount, reserveCache.nextVariableBorrowIndex); } reserve.updateInterestRates(reserveCache, params.asset, paybackAmount, 0); if (stableDebt + variableDebt - paybackAmount == 0) { userConfig.setBorrowing(reserve.id, false); } (bool isolationModeActive, address isolationModeCollateralAddress, ) = userConfig .getIsolationModeState(reserves, reservesList); if (isolationModeActive) { uint128 isolationModeTotalDebt = reserves[isolationModeCollateralAddress] .isolationModeTotalDebt; uint128 isolatedDebtRepaid = Helpers.castUint128( paybackAmount / 10 ** (reserveCache.reserveConfiguration.getDecimals() - ReserveConfiguration.DEBT_CEILING_DECIMALS) ); if (isolationModeTotalDebt <= isolatedDebtRepaid) { reserves[isolationModeCollateralAddress].isolationModeTotalDebt = 0; reserves[isolationModeCollateralAddress].isolationModeTotalDebt = isolationModeTotalDebt - isolatedDebtRepaid; } } if (params.useATokens) { IAToken(reserveCache.aTokenAddress).burn( msg.sender, reserveCache.aTokenAddress, paybackAmount, reserveCache.nextLiquidityIndex ); IERC20(params.asset).safeTransferFrom(msg.sender, reserveCache.aTokenAddress, paybackAmount); IAToken(reserveCache.aTokenAddress).handleRepayment(msg.sender, paybackAmount); } emit Repay(params.asset, params.onBehalfOf, msg.sender, paybackAmount); return paybackAmount; }
13,220,234
pragma solidity ^0.4.18; import "./Ownable.sol"; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } mapping (bytes32 => bool) proofs; // store a proof of existence in the contract state function storeProof(bytes32 proof) { proofs[proof] = true; } // calculate and store the proof for a document function notarize(string document) { var proof = calculateProof(document); storeProof(proof); } // helper function to get a document's sha256 function calculateProof(string document) returns (bytes32) { return sha256(document); } // check if a document has been notarized function checkDocument(string document) returns (bool) { var proof = calculateProof(document); return hasProof(proof); } // returns true if proof is stored function hasProof(bytes32 proof) returns (bool) { return proofs[proof]; } }
returns true if proof is stored
function hasProof(bytes32 proof) returns (bool) { return proofs[proof]; }
13,069,943
./partial_match/100/0x2bF7042E876453119B0F9B019c36c4f8A2334e61/sources/StakingAuRa.sol
The internal function used by the `_stake` and `moveStake` functions. See the `stake` public function for more details. _poolStakingAddress The staking address of the pool where the tokens/coins should be staked. _staker The staker's address. _amount The amount of tokens/coins to be staked.
) internal gasPriceIsValid onlyInitialized { address poolMiningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); require(poolMiningAddress != address(0)); require(_poolStakingAddress != address(0)); require(_amount != 0); require(!validatorSetContract.isValidatorBanned(poolMiningAddress)); require(areStakeAndWithdrawAllowed()); address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0); uint256 newStakeAmount = stakeAmount[_poolStakingAddress][delegatorOrZero].add(_amount); function _stake(address _toPoolStakingAddress, uint256 _amount) internal; function _stake( address _poolStakingAddress, address _staker, uint256 _amount if (_staker == _poolStakingAddress) { require(newStakeAmount >= candidateMinStake); require(newStakeAmount >= delegatorMinStake); require(stakeAmount[_poolStakingAddress][address(0)] != 0); } stakeAmount[_poolStakingAddress][delegatorOrZero] = newStakeAmount; _stakeAmountByEpoch[_poolStakingAddress][delegatorOrZero][stakingEpoch] = stakeAmountByCurrentEpoch(_poolStakingAddress, delegatorOrZero).add(_amount); stakeAmountTotal[_poolStakingAddress] = stakeAmountTotal[_poolStakingAddress].add(_amount); uint256 delegatorPoolsLength = delegatorPools.length; uint256 index = _delegatorPoolsIndexes[_staker][_poolStakingAddress]; bool neverStakedBefore = index >= delegatorPoolsLength || delegatorPools[index] != _poolStakingAddress; } else { _addPoolActive(_poolStakingAddress, _poolStakingAddress != validatorSetContract.unremovableValidator()); } else { _addPoolDelegator(_poolStakingAddress, _staker); _snapshotDelegatorStake(_poolStakingAddress, _staker); address[] storage delegatorPools = _delegatorPools[_staker]; if (neverStakedBefore) { _delegatorPoolsIndexes[_staker][_poolStakingAddress] = delegatorPoolsLength; delegatorPools.push(_poolStakingAddress); } if (delegatorPoolsLength == 0) { require(!validatorSetContract.hasEverBeenMiningAddress(_staker)); } }
16,646,254
./partial_match/1/0xdbc61a1685C6F70c11cBb7da70338352b1Fa4d51/sources/DigiDaigakuGiantDragons.sol
IURIInitializer Limit Break, Inc. Allows cloneable contracts to include a base uri and suffix uri./
interface IURIInitializer is IERC165 { function initializeURI(string memory baseURI_, string memory suffixURI_) external; } }
15,729,293
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** * Defines 4 roles Donor, Client, CSO, and Agent for sending around value. * The Donor mints tokens by sending a wire transfer to the Client who holds the underlying money. * The Donor can then give those tokens to the CSO to pay for things in the conflict zone. * The CSOs can cash out their tokens with Agents in the conflict zone. * Agents cash out thier tokens with the Client outside the conflict zone, at which point the Client can burn the tokens. * TODO for all the functions that require some external flow (eg wire transfer, cash exchange) we should add some type of confirmation * TODO investigate OpenZepplin AccessControl - at first glance it didn't match our needs but should investigate again */ contract HawalaCoin is ERC1155, ERC1155Receiver, ERC1155Holder, Ownable { using Counters for Counters.Counter; Counters.Counter _tokenCounter; mapping(address => Role) public users; enum Role {NONE, DONOR, CLIENT, CSO, AGENT} Counters.Counter _missionCounter; struct Mission { address csoAddr; address agentAddr; uint256 tokenId; uint256 amount; bool completed; } mapping(uint256 => Mission) public missions; // TODO add events /** * Called by the contract owner */ constructor() ERC1155("") {} /** * Bubble supportsInterface down the class hierarchy */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC1155Receiver) returns (bool) { return super.supportsInterface(interfaceId); } /** * TODO add rules: * 1) DONOR can only be added by contract owner * 2) CLIENT can only be added by DONOR * 3) CSO can only be added by DONOR * 4) AGENT can only be added by CLIENT * TODO add check if user already exists - error or update? */ function addUser(address addr, Role role) public { users[addr] = role; } /** * Mints an amount of new tokens for the Donor which are redeamable at the Client * TODO add rule: only Donor can call * TODO add currency field, right now we assume amount in USD in pennies * TODO add some type of verification/confirmation to ensure minted tokens truly reflect new bank balance */ function mint(address donorAddr, address clientAddr, uint256 amount) public { require(donorAddr == msg.sender, "Sender must match the donorAddr"); uint256 tokenId = _tokenCounter.current(); _tokenCounter.increment(); _mint(donorAddr, tokenId, amount, abi.encodePacked(clientAddr)); } /** * TODO add rule: only Client can call */ function burn(address clientAddr, uint256 tokenId, uint256 amount) public { require(clientAddr == msg.sender, "Sender must match the clientAddr"); _burn(msg.sender, tokenId, amount); } /** * TODO add rule: only CSO can call * Creates mission for a specific agent and transfers tokens to contract for escrow */ function createMission(address csoAddr, address agentAddr, uint256 tokenId, uint256 amount) public { require(csoAddr == msg.sender, "Sender must match the csoAddr"); uint256 missionId = _missionCounter.current(); missions[missionId] = Mission({ csoAddr: csoAddr, agentAddr: agentAddr, tokenId: tokenId, amount: amount, completed: false }); _missionCounter.increment(); this.safeTransferFrom(csoAddr, address(this), tokenId, amount, ""); } /** * TODO add rule: only Agent can call * TODO add functionality to allow for partial mission completions which would return some amount back to CSO */ function completeMission(address agentAddr, uint256 missionId) public { require(agentAddr == msg.sender, "Sender must match the agentAddr"); uint256 tokenId = missions[missionId].tokenId; uint256 amount = missions[missionId].amount; missions[missionId].completed = true; this.safeTransferFrom(address(this), agentAddr, tokenId, amount, ""); } /** * Convinience function to get the current token id so we can loop through all previous tokens */ function currentTokenId() public view returns (uint256) { return _tokenCounter.current(); } /** * Convinience function to get the current missions id so we can loop through all previous missions */ function currentMissionId() public view returns (uint256) { return _missionCounter.current(); } }
Convinience function to get the current missions id so we can loop through all previous missions/
function currentMissionId() public view returns (uint256) { return _missionCounter.current(); }
15,859,742
./full_match/80001/0xEE51AC33a7258ce51E2ff4A3DcAbb629b1B6A858/sources/contracts/NFT.sol
transfer NCT amount of NAME_CHANGE_PRICE from caller to _nctAddress If already named, dereserve old name
function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); _tokenAddress.transferFrom(_msgSender(), address(this), NAME_CHANGE_PRICE); if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; emit NameChange(tokenId, newName); }
5,555,647
/** *Submitted for verification at Etherscan.io on 2022-04-11 */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ pragma solidity ^0.7.0; contract GeniculateBlue is ERC721, Ownable { constructor() ERC721("Geniculate Blue", "LGN") {} using SafeMath for uint256; uint256 public constant nftPrice = 550000000000000000; uint public constant MAX_PURCHASE = 11; uint256 public constant MAX_MAIN = 475; bool public saleIsActive = false; uint public teamReserve = 15; function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function reserve(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= teamReserve, "More."); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } teamReserve = teamReserve.sub(_reserveAmount); } function mint(uint _numberOfTokens) public payable { require(saleIsActive, "Not Active."); require(_numberOfTokens <= MAX_PURCHASE, "Exceeded limit."); require(totalSupply().add(_numberOfTokens) <= MAX_MAIN, "Too many minted."); require(msg.value >= nftPrice, "More Ethereum."); for(uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_MAIN) { _safeMint(msg.sender, mintIndex); } } } string public mintedCode; bool public isReconstructed = false; mapping (uint256 => string) public geniculateSeeds; mapping (uint256 => bool) public seedSet; mapping (uint => string) public mintedColors; event SeedWritten (uint256 indexed nameIndex, string newName); function setSeed(uint256 _tokenId, string calldata currName) public { address owner = ownerOf(_tokenId); require(msg.sender == owner, "Incorrect."); require(seedSet[_tokenId] == false, "Name given."); seedSet[_tokenId] = true; geniculateSeeds[_tokenId] = currName; emit SeedWritten(_tokenId, currName); } function viewSeed(uint _tokenId) public view returns(string memory){ return geniculateSeeds[_tokenId]; } function setCode(string calldata currName) public onlyOwner { mintedCode = currName; } function viewCode() public view returns(string memory) { return mintedCode; } function setColors(uint palette, string calldata palette_param) public onlyOwner { mintedColors[palette] = palette_param; } function viewColors(uint palette) public view returns(string memory) { return mintedColors[palette]; } }
Sets `_tokenURI` as the tokenURI of `tokenId`. Requirements: - `tokenId` must exist./
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; }
2,048,213
./full_match/43113/0xA8aDCcAc7099e2859ad1AF9FFC1a213cD3576CeE/sources/contracts/WOOFI.sol
split amount to fee and transfer amount Transfer the amount with 1% from the initial amount reflection feetest
function _transfer( address sender, address recipient, uint256 amount) internal override { require(sender != address(0), "WOLFI: transfer from the zero address"); require(recipient != address(0), "WOLFI: transfer to the zero address"); require(amount > 0, "WOLFI: Transfer amount must be greater than zero"); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); (uint256 fee, uint256 transferAmount) = _splitAmount(amount); _transferStandard(sender, recipient, transferAmount, amount); uint256 currentFee = _transferToExcluded(sender, address(this), fee); uint256 initGBBalance = IERC20(rewardToken) .balanceOf(address(this)); bool isSuccess = _swapTokensForGB(currentFee); if (isSuccess) { uint256 currentGBBalance = IERC20(rewardToken) .balanceOf(address(this)) .sub(initGBBalance); uint256 liqTokens = currentGBBalance.div(4); swapAndLiquify(liqTokens); uint256 daoTokens = currentGBBalance.sub(liqTokens); IERC20(rewardToken).transfer(_DAOWalletAddress, daoTokens); } }
7,115,501
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC20/IERC20.sol"; import "./BootERC20.sol"; import "./utils/Context.sol"; contract NFTXStaking { /// @dev Emitted when NFTX is staked event NFTXStaked (address indexed user, uint256 amount); /// @dev Emitted when NFTX is unstaked event NFTXUnstaked (address indexed user, uint256 amount); IERC20 public immutable NFTX; BootERC20 public immutable BOOT; /// @dev The block number at which the staking ends, no staking after this timestamp. uint256 public immutable STAKING_END_TIME_BLOCK_NUMBER; uint256 private constant DECIMAL_MULTIPLIER = 10**18; /// @dev The amount of BOOT minted per block uint256 private _interestRatePerBlock = DECIMAL_MULTIPLIER * 100; struct UserStakeInfo { uint256 amount; uint256 rewardDebt; uint256 bootEarned; } mapping (address => UserStakeInfo) private _userStakes; /// @dev Reward mechanism management variables uint256 private _accAmountPerShare; uint256 private _totalProductivity; uint256 private _lastRewardBlock; uint256 private _totalStakedAmount; /// @notice The constructor - does the token initialization and calculates the STAKING_END_TIME_BLOCK_NUMBER /// @param NFTX_TOKEN The address of the NFTX token /// @param BOOT_TOKEN The address of the BOOT token /// @param mintingBlocks The amount of blocks that the minting is allowed for constructor(address NFTX_TOKEN, address BOOT_TOKEN, uint256 mintingBlocks) { BOOT = BootERC20(BOOT_TOKEN); NFTX = IERC20(NFTX_TOKEN); STAKING_END_TIME_BLOCK_NUMBER = block.number + mintingBlocks; } // ========== MODIFIERS ========== /// @dev Throws if called after the STAKING_END_TIME_BLOCK_NUMBER modifier onlyIfNotStakingEnded() { require(block.number <= STAKING_END_TIME_BLOCK_NUMBER, "NFTXStaking: Staking ended"); _; } // ========== STAKING AND REWARDS ========== /// @dev Stake the requested NFTX amount to the contract /// @param _amount The amount to stake /// @return _success Whether the staking was successful function stakeNFTX(uint256 _amount) public onlyIfNotStakingEnded returns (bool _success){ require(_amount > 0, 'NFTXStaking: NFTX staking amount must be greater than 0.'); require(NFTX.balanceOf(msg.sender) >= _amount, "NFTXStaking: Not enough NFTX balance."); // take the user's amount NFTX.transferFrom(msg.sender, address(this), _amount); UserStakeInfo storage userStakeInfo = _userStakes[msg.sender]; // update contract state update(); if (userStakeInfo.amount > 0) { // send the user rewards up until this point _rewardUser(msg.sender); } _totalProductivity = _totalProductivity + _amount; userStakeInfo.amount = userStakeInfo.amount + _amount; userStakeInfo.rewardDebt = _getRewardDebt(msg.sender); _totalStakedAmount = _totalStakedAmount + _amount; emit NFTXStaked(msg.sender, _amount); return true; } /// @dev Unstake the requested NFTX amount from the contract /// @param _amount The amount to unstake /// @return _success Whether the unstaking was successful function unstakeNFTX(uint256 _amount) public returns (bool _success) { require(_amount > 0, 'NFTXStaking: NFTX unstake amount must be greater than 0.'); UserStakeInfo storage userStakeInfo = _userStakes[msg.sender]; require(userStakeInfo.amount >= _amount, "NFTXStaking: Requested NFTX amount greater than the available amount."); update(); // send the user's pending amount _rewardUser(msg.sender); userStakeInfo.amount = userStakeInfo.amount - _amount; userStakeInfo.rewardDebt = _getRewardDebt(msg.sender); _totalProductivity = _totalProductivity - _amount; NFTX.transfer(msg.sender, _amount); _totalStakedAmount = _totalStakedAmount - _amount; emit NFTXUnstaked(msg.sender, _amount); return true; } /// @dev Update the internal state of the contract, used for updating the variables for the rewards mechanism function update() internal { if (block.number <= _lastRewardBlock) { return; } if (_totalProductivity == 0) { // there is nothing to be rewarded _lastRewardBlock = block.number; return; } uint256 rewards = 0; uint256 latestBlockNumber = block.number; if(latestBlockNumber > STAKING_END_TIME_BLOCK_NUMBER) { latestBlockNumber = STAKING_END_TIME_BLOCK_NUMBER; } uint256 blocksSinceLastReward = latestBlockNumber - _lastRewardBlock; rewards = blocksSinceLastReward * _interestRatePerBlock; _accAmountPerShare = _getAccAmountPerShare(rewards); // mint rewards to contract, to distribute later BOOT.mint(address(this), rewards); _lastRewardBlock = latestBlockNumber; } // ========== HELPER FUNCTIONS ========== /// @dev Calculates and sends the pending rewards to user /// @param _user The address of the user function _rewardUser(address _user) internal { uint256 pendingAmount = _getPendingAmount(_user); BOOT.transfer(_user, pendingAmount); _userStakes[_user].bootEarned += pendingAmount; } /// @dev Calculate the pending rewards amount for user /// @param _user The user's address /// @return _pendingAmount The user's pending amount function _getPendingAmount(address _user) internal view returns (uint256 _pendingAmount) { return (_userStakes[_user].amount * _accAmountPerShare) / DECIMAL_MULTIPLIER - _userStakes[_user].rewardDebt; } /// @dev Calculate the reward debt for user /// @param _user The user's address /// @return _rewardDebt The user's reward debt function _getRewardDebt(address _user) internal view returns (uint256 _rewardDebt) { return (_userStakes[_user].amount * _accAmountPerShare) / DECIMAL_MULTIPLIER; } /// @dev Calculate the accumulative amount per share based on the unclaimed rewards /// @param _rewards The unclaimed rewards /// @return accAmountPerShare The accumulative amount per share function _getAccAmountPerShare(uint256 _rewards) internal view returns (uint256 accAmountPerShare) { return _accAmountPerShare + ((_rewards * DECIMAL_MULTIPLIER) / _totalProductivity); } // ========== VIEW FUNCTIONS / METADATA ========== /// @dev Calculates the user's unclaimed rewards (the rewards from NFTX staking, which are not claimed yet). /// @param _user The address of the user /// @return _unclaimedRewards The user's uncalimed rewards. function getUnclaimedRewards(address _user) external view returns (uint256 _unclaimedRewards) { UserStakeInfo storage userStakeInfo = _userStakes[_user]; uint256 accAmountPerShare = _accAmountPerShare; if (block.number > _lastRewardBlock && _totalProductivity != 0) { uint256 blocksSinceLastReward = block.number - _lastRewardBlock; if(block.number > STAKING_END_TIME_BLOCK_NUMBER) { blocksSinceLastReward = STAKING_END_TIME_BLOCK_NUMBER - _lastRewardBlock; } uint256 reward = blocksSinceLastReward * _interestRatePerBlock; accAmountPerShare = _getAccAmountPerShare(reward); } return (userStakeInfo.amount * accAmountPerShare) / DECIMAL_MULTIPLIER - userStakeInfo.rewardDebt; } /// @dev Return the accumulative amount per share /// @return accAmountPerShare Accumulative amount per share function accumulativeAmountPerShare() external view returns (uint256 accAmountPerShare) { return _accAmountPerShare; } /// @dev Return the total productivity /// @return _totalProd Total productivity function totalProductivity() external view returns (uint256 _totalProd) { return _totalProductivity; } /// @dev Return the block of the last reward /// @return _lastRewardBlck The last reward block function lastRewardBlock() external view returns (uint256 _lastRewardBlck) { return _lastRewardBlock; } /// @dev Return the user's staked amount /// @param _user The address of the user /// @return stakedAmount The user's current staked amount function getStakedAmount(address _user) external view returns (uint256 stakedAmount) { return _userStakes[_user].amount; } /// @dev Return the user's total earned BOOT amount /// @param _user The address of the user /// @return bootEarned The user's total earned BOOT amount function getBootEarned(address _user) external view returns (uint256 bootEarned) { return _userStakes[_user].bootEarned; } /// @dev Returns the amount of BOOT tokens minted per block /// @return bootMined The amount of BOOT tokens minted per block function getBootMintedPerBlock() external view returns (uint256 bootMined) { return _interestRatePerBlock; } /// @dev Returns the blocks left until the staking ends /// @return numberOfBlocksLeft Number of blocks until the staking ends function getNumberOfBlocksLeft() external view returns (uint256 numberOfBlocksLeft) { return STAKING_END_TIME_BLOCK_NUMBER - block.number; } /// @dev Returns the total staked amount /// @return totalStakedAmount The total staked amount function getTotalStakedAmount() external view returns (uint256 totalStakedAmount) { return _totalStakedAmount; } } // 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 "./ERC20/ERC20.sol"; import "./access/Ownable.sol"; import "hardhat/console.sol"; contract BootERC20 is ERC20, Ownable { string private constant _tokenName = "Bootleg NFT"; string private constant _tokenSymbol = "BOOT"; constructor() ERC20(_tokenName, _tokenSymbol) { } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } } // 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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "./IERC20.sol"; import "hardhat/console.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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()] - 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - 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); _balances[sender] = _balances[sender] - amount; _balances[recipient] = _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 = _totalSupply + amount; _balances[account] = _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); _balances[account] = _balances[account] - amount; _totalSupply = _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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } }
Return the total productivity return _totalProd Total productivity
function totalProductivity() external view returns (uint256 _totalProd) { return _totalProductivity; }
6,863,755
./full_match/1/0xA16bE8d32934a9AaB272102AC4BB890481F4074E/sources/src/PrivatePool.sol
Changes a set of NFTs that the caller owns for another set of NFTs in the pool. The caller must approve the pool to transfer the NFTs. The sum of the caller's NFT weights must be greater than or equal to the sum of the output pool NFTs weights. The caller must also pay a fee depending the net input weight and change fee amount. inputTokenIds The token IDs of the NFTs to change. inputTokenWeights The weights of the NFTs to change. inputProof The merkle proof for the weights of each NFT to change. stolenNftProofs The proofs that show each input NFT is not stolen. outputTokenIds The token IDs of the NFTs to receive. outputTokenWeights The weights of the NFTs to receive. outputProof The merkle proof for the weights of each NFT to receive. return feeAmount The amount of base tokens to pay in fees. return protocolFeeAmount The amount of base tokens to pay in protocol fees. ~~~ Checks ~~~ check that the caller sent 0 ETH if base token is not ETH check that NFTs are not stolen fix stack too deep calculate the sum of weights for the input nfts calculate the sum of weights for the output nfts check that the input weights are greater than or equal to the output weights calculate the fee amount transfer the fee amount of base tokens from the caller if the protocol fee is non-zero then transfer the protocol fee to the factory check that the caller sent enough ETH to cover the fee amount and protocol fee if the protocol fee is non-zero then transfer the protocol fee to the factory refund any excess ETH to the caller transfer the input nfts from the caller transfer the output nfts to the caller
function change( uint256[] memory inputTokenIds, uint256[] memory inputTokenWeights, MerkleMultiProof memory inputProof, IStolenNftOracle.Message[] memory stolenNftProofs, uint256[] memory outputTokenIds, uint256[] memory outputTokenWeights, MerkleMultiProof memory outputProof ) public payable returns (uint256 feeAmount, uint256 protocolFeeAmount) { if (baseToken != address(0) && msg.value > 0) revert InvalidEthAmount(); if (useStolenNftOracle) { IStolenNftOracle(stolenNftOracle).validateTokensAreNotStolen(nft, inputTokenIds, stolenNftProofs); } { uint256 inputWeightSum = sumWeightsAndValidateProof(inputTokenIds, inputTokenWeights, inputProof); uint256 outputWeightSum = sumWeightsAndValidateProof(outputTokenIds, outputTokenWeights, outputProof); if (inputWeightSum < outputWeightSum) revert InsufficientInputWeight(); (feeAmount, protocolFeeAmount) = changeFeeQuote(inputWeightSum); } if (baseToken != address(0)) { ERC20(baseToken).safeTransferFrom(msg.sender, address(this), feeAmount); if (protocolFeeAmount > 0) ERC20(baseToken).safeTransferFrom(msg.sender, factory, protocolFeeAmount); if (msg.value < feeAmount + protocolFeeAmount) revert InvalidEthAmount(); if (protocolFeeAmount > 0) factory.safeTransferETH(protocolFeeAmount); if (msg.value > feeAmount + protocolFeeAmount) { msg.sender.safeTransferETH(msg.value - feeAmount - protocolFeeAmount); } } for (uint256 i = 0; i < inputTokenIds.length; i++) { ERC721(nft).safeTransferFrom(msg.sender, address(this), inputTokenIds[i]); } for (uint256 i = 0; i < outputTokenIds.length; i++) { ERC721(nft).safeTransferFrom(address(this), msg.sender, outputTokenIds[i]); } }
9,718,432
pragma solidity ^0.8.4; contract Rx { //structure to hold the details of a prescriber struct Prescriber { string name; //name of prescriber string mcr; //MCR of prescriber string clinicName; //name of clinic string clinicAddress; //address of clinic address addr; //address of prescriber bool valid; //valid status } //structure to hold the details of a patient struct Patient { string name; //name of patient string ic; //IC of patient uint birthDate; //birth date of patient string homeAddress; //home address of patient address addr; //address of patient uint[] prescriptionList; //prescription list of patient bool valid; //valid status } //structure to hold the details of a pharmacist struct Pharmacist { string name; //name of pharmacist string prn; //PRN of pharmacist string clinicName; //name of clinic string clinicAddress; //address of clinic address addr; //address of pharmacist bool valid; //valid status } //structure to hold the details of a prescribed medication struct Drug { string name; //name of drug string strength; //strength of drug string dosing; //dosing frequency of drug uint duration; //duration of use uint quantity; //quantity of drug prescribed bool modified; //modified status [COUNTER???] uint dispenseCounter; //counter mapping(uint => Dispense) dispenseStructs; // random access by dispense key uint balance; //balance bool valid; //valid status } //structure to hold Rx details struct Prescription { uint date; //date of Rx Patient patientDetails; //details of patient Prescriber prescriberDetails; //details of prescriber uint[] drugList; //list of drug keys so we can look them up mapping(string => uint) drugNames; // mapping drug name to drug key mapping(uint => Drug) drugStructs; // random access by drug key bool valid; //valid status bool reviewed; //reviewed status } //structure to hold the details of a dispensed drug struct Dispense { uint dispensedDate; //date of dispensing uint dispensedQuantity; //quantity of drug dispensed uint dispensedDuration; //duration of drug dispensed bool dispensed; // dispensed status } mapping(address => Prescriber) public prescriberStructs; //access by prescriber address address[] public prescriberList; //list of prescriber address so we can enumerate them mapping(address => Patient) public patientStructs; //access by patient address address[] patientList; //list of patient address so we can enumerate them mapping(address => Pharmacist) public pharmacistStructs; //access by pharmacist address address[] pharmacistList; //list of pharmacist address so we can enumerate them mapping(uint => Prescription) public prescriptionStructs; //access by prescription key uint[] prescriptionList; //list of prescription keys so we can enumerate them address public admin; //owner of the smart contract uint drugCount; //for addDrug uint prescriptionCount; //for newPrescription uint dispenseCount; //for dispenseDrug constructor() { admin = msg.sender; } //function can only run if user is admin modifier onlyAdmin { require(msg.sender == admin, "You are not authorised for this action"); _; } //function can only run if user is prescriber modifier onlyPrescriber { address addr = msg.sender; require(prescriberStructs[addr].valid, "You are not authorised for this action"); _; } //function can only run if user is pharmacist modifier onlyPharmacist { address addr = msg.sender; require(pharmacistStructs[addr].valid, "You are not authorised for this action"); _; } //adding a prescriber - require to be admin function setPrescriber(string memory _name, string memory _mcr, string memory _clinicName, string memory _clinicAddress, address _addr) public onlyAdmin { prescriberStructs[_addr] = Prescriber({ name: _name, mcr: _mcr, clinicName: _clinicName, clinicAddress: _clinicAddress, addr: _addr, valid: true }); prescriberList.push(_addr); } //update a prescriber - require to be admin function updatePrescriber(string memory _name, string memory _mcr, string memory _clinicName, string memory _clinicAddress, address _addr) public onlyAdmin { require(prescriberStructs[_addr].valid, "User is no longer valid"); //require prescriber to be valid Prescriber storage p = prescriberStructs[_addr]; p.name = _name; p.mcr = _mcr; p.clinicName = _clinicName; p.clinicAddress = _clinicAddress; } //adding a patient - require to be admin function setPatient(string memory _name, string memory _ic, uint _birthDate, string memory _homeAddress, address _addr) public onlyAdmin { patientStructs[_addr] = Patient({ name: _name, ic: _ic, birthDate: _birthDate, homeAddress: _homeAddress, addr: _addr, valid: true, prescriptionList: new uint[](0) }); patientList.push(_addr); } //update a patient - require to be admin function updatePatient(string memory _name, string memory _ic, uint _birthDate, string memory _homeAddress, address _addr) public onlyAdmin { require(patientStructs[_addr].valid, "User is no longer valid"); //require patient to be valid Patient storage p = patientStructs[_addr]; p.name = _name; p.ic = _ic; p.birthDate = _birthDate; p.homeAddress = _homeAddress; } //adding a pharmacist - require to be admin function setPharmacist(string memory _name, string memory _prn, string memory _clinicName, string memory _clinicAddress, address _addr) public onlyAdmin { pharmacistStructs[_addr] = Pharmacist({ name: _name, prn: _prn, clinicName: _clinicName, clinicAddress: _clinicAddress, addr: _addr, valid: true }); pharmacistList.push(_addr); } //update a pharmacist - require to be admin function updatePharmacist(string memory _name, string memory _prn, string memory _clinicName, string memory _clinicAddress, address _addr) public onlyAdmin { require(pharmacistStructs[_addr].valid, "User is no longer valid"); //require pharmacist to be valid Pharmacist storage p = pharmacistStructs[_addr]; p.name = _name; p.prn = _prn; p.clinicName = _clinicName; p.clinicAddress = _clinicAddress; } //creating a prescription - require to be prescriber function newPrescription(address _prescriberAddr, address _patientAddr) public onlyPrescriber { prescriptionCount = prescriptionList.length; prescriptionCount++; prescriptionList.push(prescriptionCount); patientStructs[_patientAddr].prescriptionList.push(prescriptionCount); Prescription storage p = prescriptionStructs[prescriptionCount]; p.date = block.timestamp; p.prescriberDetails = prescriberStructs[_prescriberAddr]; p.patientDetails = patientStructs[_patientAddr]; p.valid = true; p.reviewed = false; p.drugList = new uint[](0); } //adding a drug to prescription - require to be prescriber function addDrug(uint _prescriptionKey, string memory _drugName, string memory _strength, string memory _dosing, uint _duration, uint _quantity) public onlyPrescriber { require(prescriptionStructs[_prescriptionKey].valid, "Prescription is no longer valid"); //require rx to be valid drugCount = prescriptionStructs[_prescriptionKey].drugList.length; //get existing max drug key drugCount++; prescriptionStructs[_prescriptionKey].drugList.push(drugCount); //add drug key to prescription drug list prescriptionStructs[_prescriptionKey].drugNames[_drugName] = drugCount; //mapping drug name to drug key Drug storage d = prescriptionStructs[_prescriptionKey].drugStructs[drugCount]; d.name = _drugName; d.strength = _strength; d.dosing = _dosing; d.duration = _duration; d.quantity = _quantity; d.modified = false; d.dispenseCounter = 0; d.valid = true; d.balance = _quantity; //balance if it is by duration } //remove a drug from prescription - require to be prescriber function removeDrug(uint _prescriptionKey, uint _drugKey) public onlyPrescriber { require(prescriptionStructs[_prescriptionKey].valid, "Prescription is no longer valid"); //require rx to be valid prescriptionStructs[_prescriptionKey].drugStructs[_drugKey].valid = false; } //update a drug in prescription - require to be prescriber function updateDrug(uint _prescriptionKey, uint _drugKey, string memory _drugName, string memory _strength, string memory _dosing, uint _duration, uint _quantity) public onlyPrescriber { require(prescriptionStructs[_prescriptionKey].valid, "Prescription is no longer valid"); //require rx to be valid Drug storage d = prescriptionStructs[_prescriptionKey].drugStructs[_drugKey]; d.name = _drugName; d.strength = _strength; d.dosing = _dosing; d.duration = _duration; d.quantity = _quantity; d.modified = true; d.balance = _quantity; //balance if it is by duration } //dispense a drug in prescription - require to be pharmacist function dispenseDrug(uint _prescriptionKey, uint _drugKey, uint _dispensedQuantity, uint _dispensedDuration) public onlyPharmacist { require(prescriptionStructs[_prescriptionKey].valid, "Prescription is no longer valid"); //require rx to be valid dispenseCount = prescriptionStructs[_prescriptionKey].drugStructs[_drugKey].dispenseCounter; dispenseCount++; //+1 to dispense counter prescriptionStructs[_prescriptionKey].drugStructs[_drugKey].dispenseCounter = dispenseCount; //update dispense coumter //conditions to check if quantity or duration is selected Dispense storage dp = prescriptionStructs[_prescriptionKey].drugStructs[_drugKey].dispenseStructs[dispenseCount]; dp.dispensedDate = block.timestamp; dp.dispensedQuantity = _dispensedQuantity; dp.dispensedDuration = _dispensedDuration; dp.dispensed = true; uint _quantity = prescriptionStructs[_prescriptionKey].drugStructs[_drugKey].quantity; prescriptionStructs[_prescriptionKey].drugStructs[_drugKey].balance = _quantity - _dispensedQuantity; //balance if dispensing by duration } //check if prescription is valid function checkValid(uint _prescriptionKey) public { uint _nowDate = block.timestamp; if (_nowDate - prescriptionStructs[_prescriptionKey].date > 31536000) { //if prescription is more than 1 year old prescriptionStructs[_prescriptionKey].valid = false; } else { prescriptionStructs[_prescriptionKey].valid = true; } } //review prescription - require to be pharmacist function reviewPrescription(uint _prescriptionKey) public onlyPharmacist { prescriptionStructs[_prescriptionKey].reviewed = true; } //check for changes in drugs prescribed from another prescription - runs after getPrescriptionDrugs function checkChanges(uint _prescriptionKey, string memory _drugName) public view returns (uint, string memory, string memory, string memory) { uint _drugKey; //drug key of similar drug in other prescription string memory _name; //name of drug string memory _strength; //strength of drug string memory _dosing; //dosing of drug if (prescriptionStructs[_prescriptionKey].drugNames[_drugName] > 0) { //if _drugName exists in another prescription, drug key is >0 _drugKey = prescriptionStructs[_prescriptionKey].drugNames[_drugName]; _name = prescriptionStructs[_prescriptionKey].drugStructs[_drugKey].name; _strength = prescriptionStructs[_prescriptionKey].drugStructs[_drugKey].strength; _dosing = prescriptionStructs[_prescriptionKey].drugStructs[_drugKey].dosing; } return (_drugKey, _name, _strength, _dosing); } //remove prescription - require to be prescriber function removePrescription(uint _prescriptionKey) public onlyPrescriber { prescriptionStructs[_prescriptionKey].valid = false; } //remove prescriber - require to be admin function removePrescriber(address _addr) public onlyAdmin { prescriberStructs[_addr].valid = false; } //remove prescriber - require to be admin function removePatient(address _addr) public onlyAdmin { patientStructs[_addr].valid = false; } //remove prescriber - require to be admin function removePharmacist(address _addr) public onlyAdmin { pharmacistStructs[_addr].valid = false; } //retrieving admin function getAdmin() public view returns (address) { return admin; } //get list of patient addr function getPatientList() public view returns (address[] memory) { return patientList; } //get list of prescriber addr function getPrescriberList() public view returns (address[] memory) { return prescriberList; } //get list of pharmacist addr function getPharmacistList() public view returns (address[] memory) { return pharmacistList; } //get list of prescription function getPrescriptionList() public view returns (uint[] memory) { return prescriptionList; } //get prescriber name from addr function getPrescriberName(address _addr) public view returns (string memory) { return prescriberStructs[_addr].name; } //get list of patient prescriptions function getPatientPrescrptionList(address _addr) public view returns (uint[] memory) { return patientStructs[_addr].prescriptionList; } //get overview of patient's prescription function getPatientPrescrptionOverview(uint _prescriptionKey) public view returns (uint, string memory, string memory, bool, bool) { uint _date; //date of Rx string memory _prescriberName; //name of prescriber string memory _prescriberClinic; //name of prescriber bool _valid; //valid status bool _reviewed; //reviewed status _date = prescriptionStructs[_prescriptionKey].date; _prescriberName = prescriptionStructs[_prescriptionKey].prescriberDetails.name; _prescriberClinic = prescriptionStructs[_prescriptionKey].prescriberDetails.clinicName; _valid = prescriptionStructs[_prescriptionKey].valid; _reviewed = prescriptionStructs[_prescriptionKey].reviewed; return (_date, _prescriberName, _prescriberClinic, _valid, _reviewed); } //get prescribed drug keys function getPrescriptionDrugKeys(uint _prescriptionKey) public view returns (uint[] memory) { uint[] memory _drugKeys = prescriptionStructs[_prescriptionKey].drugList; return _drugKeys; } //get drug details part 1 - name, stength, dosing, duration/quantity function getPrescriptionDrugDetailsPart1(uint _prescriptionKey, uint _drugKey) public view returns (string memory, string memory, string memory, uint, uint) { string memory _name; //drug name string memory _strength; string memory _dosing; uint _duration; uint _quantity; Prescription storage p = prescriptionStructs[_prescriptionKey]; Drug storage d = p.drugStructs[_drugKey]; _name = d.name; _strength = d.strength; _dosing = d.dosing; _duration = d.duration; _quantity = d.quantity; return (_name, _strength, _dosing, _duration, _quantity); } //get drug details part 2 - modified and valid status, dispensed counter and balance function getPrescriptionDrugDetailsPart2(uint _prescriptionKey, uint _drugKey) public view returns (bool, uint, uint, bool) { bool _modified; uint _dispenseCounter; uint _balance; bool _valid; Prescription storage p = prescriptionStructs[_prescriptionKey]; Drug storage d = p.drugStructs[_drugKey]; _modified = d.modified; _dispenseCounter = d.dispenseCounter; _balance = d.balance; _valid = d.valid; return (_modified, _dispenseCounter, _balance, _valid); } //get dispensed details - date, quantity, duration, dispensed status function getDispensedDetails(uint _prescriptionKey, uint _drugKey, uint _dispenseCounter) public view returns (uint, uint, uint, bool) { uint _dispensedDate; uint _dispensedQuantity; uint _dispensedDuration; bool _dispensed; Prescription storage p = prescriptionStructs[_prescriptionKey]; Drug storage d = p.drugStructs[_drugKey]; Dispense storage dp = d.dispenseStructs[_dispenseCounter]; _dispensedDate = dp.dispensedDate; _dispensedQuantity = dp.dispensedQuantity; _dispensedDuration = dp.dispensedDuration; _dispensed = dp.dispensed; return (_dispensedDate, _dispensedQuantity, _dispensedDuration, _dispensed); } }
get list of patient addr
function getPatientList() public view returns (address[] memory) { return patientList; }
12,703,364
./partial_match/1/0x51DF59fa999b56c351B92E933aFD177Ef9c0003f/sources/Warrior.sol
prevent transfer or burn of staked id
function _beforeTokenTransfers(address /*from*/, address /*to*/, uint256 startTokenId, uint256 /*quantity*/) internal virtual override { require(tokenToIsStaked[startTokenId] == false, "Warrior, cannot transfer - currently locked"); }
3,564,070
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {IBNFT} from "../interfaces/IBNFT.sol"; import {IFlashLoanReceiver} from "../interfaces/IFlashLoanReceiver.sol"; import {StringsUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import {ERC721EnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import {IERC1155Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import {IERC721MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import {IERC721ReceiverUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import {IERC1155ReceiverUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; /** * @title BNFT contract * @dev Implements the methods for the bNFT protocol **/ contract BNFT is IBNFT, ERC721EnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { address private _underlyingAsset; // Mapping from token ID to minter address mapping(uint256 => address) private _minters; address private _owner; uint256 private constant _NOT_ENTERED = 0; uint256 private constant _ENTERED = 1; uint256 private _status; address private _claimAdmin; /** * @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 Initializes the bNFT * @param underlyingAsset_ The address of the underlying asset of this bNFT (E.g. PUNK for bPUNK) */ function initialize( address underlyingAsset_, string calldata bNftName, string calldata bNftSymbol, address owner_, address claimAdmin_ ) external override initializer { __ERC721_init(bNftName, bNftSymbol); _underlyingAsset = underlyingAsset_; _transferOwnership(owner_); _setClaimAdmin(claimAdmin_); emit Initialized(underlyingAsset_); } /** * @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(), "BNFT: 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), "BNFT: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev Returns the address of the current claim admin. */ function claimAdmin() public view virtual returns (address) { return _claimAdmin; } /** * @dev Throws if called by any account other than the claim admin. */ modifier onlyClaimAdmin() { require(claimAdmin() == _msgSender(), "BNFT: caller is not the claim admin"); _; } /** * @dev Set claim admin of the contract to a new account (`newAdmin`). * Can only be called by the current owner. */ function setClaimAdmin(address newAdmin) public virtual onlyOwner { require(newAdmin != address(0), "BNFT: new admin is the zero address"); _setClaimAdmin(newAdmin); } function _setClaimAdmin(address newAdmin) internal virtual { address oldAdmin = _claimAdmin; _claimAdmin = newAdmin; emit ClaimAdminUpdated(oldAdmin, newAdmin); } /** * @dev Mints bNFT token to the user address * * Requirements: * - The caller can be contract address and EOA * * @param to The owner address receive the bNFT token * @param tokenId token id of the underlying asset of NFT **/ function mint(address to, uint256 tokenId) external override nonReentrant { bool isCA = AddressUpgradeable.isContract(_msgSender()); if (!isCA) { require(to == _msgSender(), "BNFT: caller is not to"); } require(!_exists(tokenId), "BNFT: exist token"); require(IERC721Upgradeable(_underlyingAsset).ownerOf(tokenId) == _msgSender(), "BNFT: caller is not owner"); // mint bNFT to user _mint(to, tokenId); _minters[tokenId] = _msgSender(); // Receive NFT Tokens IERC721Upgradeable(_underlyingAsset).safeTransferFrom(_msgSender(), address(this), tokenId); emit Mint(_msgSender(), _underlyingAsset, tokenId, to); } /** * @dev Burns user bNFT token * * Requirements: * - The caller can be contract address and EOA * * @param tokenId token id of the underlying asset of NFT **/ function burn(uint256 tokenId) external override nonReentrant { require(_exists(tokenId), "BNFT: nonexist token"); require(_minters[tokenId] == _msgSender(), "BNFT: caller is not minter"); address tokenOwner = ERC721Upgradeable.ownerOf(tokenId); _burn(tokenId); delete _minters[tokenId]; IERC721Upgradeable(_underlyingAsset).safeTransferFrom(address(this), _msgSender(), tokenId); emit Burn(_msgSender(), _underlyingAsset, tokenId, tokenOwner); } /** * @dev See {IBNFT-flashLoan}. */ function flashLoan( address receiverAddress, uint256[] calldata nftTokenIds, bytes calldata params ) external override nonReentrant { uint256 i; IFlashLoanReceiver receiver = IFlashLoanReceiver(receiverAddress); // !!!CAUTION: receiver contract may reentry mint, burn, flashloan again require(receiverAddress != address(0), "BNFT: zero address"); require(nftTokenIds.length > 0, "BNFT: empty token list"); // only token owner can do flashloan for (i = 0; i < nftTokenIds.length; i++) { require(ownerOf(nftTokenIds[i]) == _msgSender(), "BNFT: caller is not owner"); } // step 1: moving underlying asset forward to receiver contract for (i = 0; i < nftTokenIds.length; i++) { IERC721Upgradeable(_underlyingAsset).safeTransferFrom(address(this), receiverAddress, nftTokenIds[i]); } // setup 2: execute receiver contract, doing something like aidrop require( receiver.executeOperation(_underlyingAsset, nftTokenIds, _msgSender(), address(this), params), "BNFT: invalid flashloan executor return" ); // setup 3: moving underlying asset backword from receiver contract for (i = 0; i < nftTokenIds.length; i++) { IERC721Upgradeable(_underlyingAsset).safeTransferFrom(receiverAddress, address(this), nftTokenIds[i]); emit FlashLoan(receiverAddress, _msgSender(), _underlyingAsset, nftTokenIds[i]); } } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { return IERC721MetadataUpgradeable(_underlyingAsset).tokenURI(tokenId); } /** * @dev See {IBNFT-contractURI}. */ function contractURI() external view override returns (string memory) { string memory hexAddress = StringsUpgradeable.toHexString(uint256(uint160(address(this))), 20); return string(abi.encodePacked("https://metadata.benddao.xyz/", hexAddress)); } function claimERC20Airdrop( address token, address to, uint256 amount ) external override nonReentrant onlyClaimAdmin { require(token != _underlyingAsset, "BNFT: token can not be underlying asset"); require(token != address(this), "BNFT: token can not be self address"); IERC20Upgradeable(token).transfer(to, amount); emit ClaimERC20Airdrop(token, to, amount); } function claimERC721Airdrop( address token, address to, uint256[] calldata ids ) external override nonReentrant onlyClaimAdmin { require(token != _underlyingAsset, "BNFT: token can not be underlying asset"); require(token != address(this), "BNFT: token can not be self address"); for (uint256 i = 0; i < ids.length; i++) { IERC721Upgradeable(token).safeTransferFrom(address(this), to, ids[i]); } emit ClaimERC721Airdrop(token, to, ids); } function claimERC1155Airdrop( address token, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external override nonReentrant onlyClaimAdmin { require(token != _underlyingAsset, "BNFT: token can not be underlying asset"); require(token != address(this), "BNFT: token can not be self address"); IERC1155Upgradeable(token).safeBatchTransferFrom(address(this), to, ids, amounts, data); emit ClaimERC1155Airdrop(token, to, ids, amounts, data); } function executeAirdrop(address airdropContract, bytes calldata airdropParams) external override nonReentrant onlyClaimAdmin { require(airdropContract != address(0), "invalid airdrop contract address"); require(airdropParams.length >= 4, "invalid airdrop parameters"); // call project aidrop contract AddressUpgradeable.functionCall(airdropContract, airdropParams, "call airdrop method failed"); emit ExecuteAirdrop(airdropContract); } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure override returns (bytes4) { operator; from; tokenId; data; return IERC721ReceiverUpgradeable.onERC721Received.selector; } function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external pure override returns (bytes4) { operator; from; id; value; data; return IERC1155ReceiverUpgradeable.onERC1155Received.selector; } function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external pure override returns (bytes4) { operator; from; ids; values; data; return IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector; } /** * @dev See {IBNFT-minterOf}. */ function minterOf(uint256 tokenId) external view override returns (address) { address minter = _minters[tokenId]; require(minter != address(0), "BNFT: minter query for nonexistent token"); return minter; } /** * @dev See {IBNFT-underlyingAsset}. */ function underlyingAsset() external view override returns (address) { return _underlyingAsset; } /** * @dev Being non transferrable, the bNFT token does not implement any of the * standard ERC721 functions for transfer and allowance. **/ function approve(address to, uint256 tokenId) public virtual override { to; tokenId; revert("APPROVAL_NOT_SUPPORTED"); } function setApprovalForAll(address operator, bool approved) public virtual override { operator; approved; revert("APPROVAL_NOT_SUPPORTED"); } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { from; to; tokenId; revert("TRANSFER_NOT_SUPPORTED"); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { from; to; tokenId; revert("TRANSFER_NOT_SUPPORTED"); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { from; to; tokenId; _data; revert("TRANSFER_NOT_SUPPORTED"); } function _transfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable) { from; to; tokenId; revert("TRANSFER_NOT_SUPPORTED"); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IBNFT { /** * @dev Emitted when an bNFT is initialized * @param underlyingAsset_ The address of the underlying asset **/ event Initialized(address indexed underlyingAsset_); /** * @dev Emitted when the ownership is transferred * @param oldOwner The address of the old owner * @param newOwner The address of the new owner **/ event OwnershipTransferred(address oldOwner, address newOwner); /** * @dev Emitted when the claim admin is updated * @param oldAdmin The address of the old admin * @param newAdmin The address of the new admin **/ event ClaimAdminUpdated(address oldAdmin, address newAdmin); /** * @dev Emitted on mint * @param user The address initiating the burn * @param nftAsset address of the underlying asset of NFT * @param nftTokenId token id of the underlying asset of NFT * @param owner The owner address receive the bNFT token **/ event Mint(address indexed user, address indexed nftAsset, uint256 nftTokenId, address indexed owner); /** * @dev Emitted on burn * @param user The address initiating the burn * @param nftAsset address of the underlying asset of NFT * @param nftTokenId token id of the underlying asset of NFT * @param owner The owner address of the burned bNFT token **/ event Burn(address indexed user, address indexed nftAsset, uint256 nftTokenId, address indexed owner); /** * @dev Emitted on flashLoan * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param nftAsset address of the underlying asset of NFT * @param tokenId The token id of the asset being flash borrowed **/ event FlashLoan(address indexed target, address indexed initiator, address indexed nftAsset, uint256 tokenId); event ClaimERC20Airdrop(address indexed token, address indexed to, uint256 amount); event ClaimERC721Airdrop(address indexed token, address indexed to, uint256[] ids); event ClaimERC1155Airdrop(address indexed token, address indexed to, uint256[] ids, uint256[] amounts, bytes data); event ExecuteAirdrop(address indexed airdropContract); /** * @dev Initializes the bNFT * @param underlyingAsset_ The address of the underlying asset of this bNFT (E.g. PUNK for bPUNK) */ function initialize( address underlyingAsset_, string calldata bNftName, string calldata bNftSymbol, address owner_, address claimAdmin_ ) external; /** * @dev Mints bNFT token to the user address * * Requirements: * - The caller can be contract address and EOA. * - `nftTokenId` must not exist. * * @param to The owner address receive the bNFT token * @param tokenId token id of the underlying asset of NFT **/ function mint(address to, uint256 tokenId) external; /** * @dev Burns user bNFT token * * Requirements: * - The caller can be contract address and EOA. * - `tokenId` must exist. * * @param tokenId token id of the underlying asset of NFT **/ function burn(uint256 tokenId) external; /** * @dev Allows smartcontracts to access the tokens within one transaction, as long as the tokens taken is returned. * * Requirements: * - `nftTokenIds` must exist. * * @param receiverAddress The address of the contract receiving the tokens, implementing the IFlashLoanReceiver interface * @param nftTokenIds token ids of the underlying asset * @param params Variadic packed params to pass to the receiver as extra information */ function flashLoan( address receiverAddress, uint256[] calldata nftTokenIds, bytes calldata params ) external; function claimERC20Airdrop( address token, address to, uint256 amount ) external; function claimERC721Airdrop( address token, address to, uint256[] calldata ids ) external; function claimERC1155Airdrop( address token, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; function executeAirdrop(address airdropContract, bytes calldata airdropParams) external; /** * @dev Returns the owner of the `nftTokenId` token. * * Requirements: * - `tokenId` must exist. * * @param tokenId token id of the underlying asset of NFT */ function minterOf(uint256 tokenId) external view returns (address); /** * @dev Returns the address of the underlying asset. */ function underlyingAsset() external view returns (address); /** * @dev Returns the contract-level metadata. */ function contractURI() external view returns (string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title IFlashLoanReceiver interface * @notice Interface for the IFlashLoanReceiver. * @author BEND * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address asset, uint256[] calldata tokenIds, address initiator, address operator, bytes calldata params ) external returns (bool); } // 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 (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 (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} /** * @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[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } /** * @dev 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[46] private __gap; } // 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: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 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 (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 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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); }
Burns user bNFT token Requirements: - The caller can be contract address and EOA tokenId token id of the underlying asset of NFT/
function burn(uint256 tokenId) external override nonReentrant { require(_exists(tokenId), "BNFT: nonexist token"); require(_minters[tokenId] == _msgSender(), "BNFT: caller is not minter"); address tokenOwner = ERC721Upgradeable.ownerOf(tokenId); _burn(tokenId); delete _minters[tokenId]; IERC721Upgradeable(_underlyingAsset).safeTransferFrom(address(this), _msgSender(), tokenId); emit Burn(_msgSender(), _underlyingAsset, tokenId, tokenOwner); }
357,732
./full_match/4/0x0A87021D82453AB0B18a375aFfdB8C689e05A182/sources/sirtoken3.sol
add or remove a pair pair_ address value_ bool true/false = add/remove/
function SetPair(address pair_, bool value_) external onlyOwner { require(pair_ != Addr[Key.PAIR], "!native pair"); _setPair(pair_, value_); }
12,424,899
./full_match/1/0xD7134e2265B78DFCF4e9FA4DC65b18F4D5C03220/sources/contracts/bridgeERC20/layerZero/utils/OFTCoreERC20.sol
@inheritdoc NonblockingLzAppERC20 decode and load the toAddresssolhint-disable-next-line
function _nonblockingLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual override { (bytes memory toAddressBytes, uint256 amount) = abi.decode(_payload, (bytes, uint256)); address toAddress; assembly { toAddress := mload(add(toAddressBytes, 20)) } amount = _creditTo(_srcChainId, toAddress, amount); emit ReceiveFromChain(_srcChainId, _srcAddress, toAddress, amount, _nonce); }
3,183,001
// File: @openzeppelin/contracts/math/SafeMath.sol // License: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // License: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/v1/AbstractFiatTokenV1.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; abstract contract AbstractFiatTokenV1 is IERC20 { function _approve( address owner, address spender, uint256 value ) internal virtual; function _transfer( address from, address to, uint256 value ) internal virtual; } // File: contracts/v1/Ownable.sol /** * License: MIT * * Copyright (c) 2018 zOS Global Limited. * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @notice The Ownable contract has an owner address, and provides basic * authorization control functions * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol * Modifications: * 1. Consolidate OwnableStorage into this contract (7/13/18) * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 3. Make public functions external (5/27/20) */ contract Ownable { // Owner of the contract address private _owner; /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The constructor sets the original owner of the contract to the sender account. */ constructor() public { setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() external view returns (address) { return _owner; } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { _owner = newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == _owner, "Ownable: caller is not the owner"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); setOwner(newOwner); } } // File: contracts/v1/Pausable.sol /** * License: MIT * * Copyright (c) 2016 Smart Contract Solutions, Inc. * Copyright (c) 2018-2020 CENTRE SECZ0 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @notice Base contract which allows children to implement an emergency stop * mechanism * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol * Modifications: * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018) * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018) * 3. Removed whenPaused (6/14/2018) * 4. Switches ownable library to use ZeppelinOS (7/12/18) * 5. Remove constructor (7/13/18) * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20) * 7. Make public functions external (5/27/20) */ contract Pausable is Ownable { event Pause(); event Unpause(); event PauserChanged(address indexed newAddress); address public pauser; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "Pausable: paused"); _; } /** * @dev throws if called by any account other than the pauser */ modifier onlyPauser() { require(msg.sender == pauser, "Pausable: caller is not the pauser"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() external onlyPauser { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() external onlyPauser { paused = false; emit Unpause(); } /** * @dev update the pauser role */ function updatePauser(address _newPauser) external onlyOwner { require( _newPauser != address(0), "Pausable: new pauser is the zero address" ); pauser = _newPauser; emit PauserChanged(pauser); } } // File: contracts/v1/Blacklistable.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title Blacklistable Token * @dev Allows accounts to be blacklisted by a "blacklister" role */ contract Blacklistable is Ownable { address public blacklister; mapping(address => bool) internal blacklisted; event Blacklisted(address indexed _account); event UnBlacklisted(address indexed _account); event BlacklisterChanged(address indexed newBlacklister); /** * @dev Throws if called by any account other than the blacklister */ modifier onlyBlacklister() { require( msg.sender == blacklister, "Blacklistable: caller is not the blacklister" ); _; } /** * @dev Throws if argument account is blacklisted * @param _account The address to check */ modifier notBlacklisted(address _account) { require( !blacklisted[_account], "Blacklistable: account is blacklisted" ); _; } /** * @dev Checks if account is blacklisted * @param _account The address to check */ function isBlacklisted(address _account) external view returns (bool) { return blacklisted[_account]; } /** * @dev Adds account to blacklist * @param _account The address to blacklist */ function blacklist(address _account) external onlyBlacklister { blacklisted[_account] = true; emit Blacklisted(_account); } /** * @dev Removes account from blacklist * @param _account The address to remove from the blacklist */ function unBlacklist(address _account) external onlyBlacklister { blacklisted[_account] = false; emit UnBlacklisted(_account); } function updateBlacklister(address _newBlacklister) external onlyOwner { require( _newBlacklister != address(0), "Blacklistable: new blacklister is the zero address" ); blacklister = _newBlacklister; emit BlacklisterChanged(blacklister); } } // File: contracts/v1/FiatTokenV1.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string memory tokenName, string memory tokenSymbol, string memory tokenCurrency, uint8 tokenDecimals, address newMasterMinter, address newPauser, address newBlacklister, address newOwner ) public { require(!initialized, "FiatToken: contract is already initialized"); require( newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); require( newPauser != address(0), "FiatToken: new pauser is the zero address" ); require( newBlacklister != address(0), "FiatToken: new blacklister is the zero address" ); require( newOwner != address(0), "FiatToken: new owner is the zero address" ); name = tokenName; symbol = tokenSymbol; currency = tokenCurrency; decimals = tokenDecimals; masterMinter = newMasterMinter; pauser = newPauser; blacklister = newBlacklister; setOwner(newOwner); initialized = true; } /** * @dev Throws if called by any account other than a minter */ modifier onlyMinters() { require(minters[msg.sender], "FiatToken: caller is not a minter"); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. Must be less than or equal * to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) returns (bool) { require(_to != address(0), "FiatToken: mint to the zero address"); require(_amount > 0, "FiatToken: mint amount not greater than 0"); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require( _amount <= mintingAllowedAmount, "FiatToken: mint amount exceeds minterAllowance" ); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Throws if called by any account other than the masterMinter */ modifier onlyMasterMinter() { require( msg.sender == masterMinter, "FiatToken: caller is not the masterMinter" ); _; } /** * @dev Get minter allowance for an account * @param minter The address of the minter */ function minterAllowance(address minter) external view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks if account is a minter * @param account The address to check */ function isMinter(address account) external view returns (bool) { return minters[account]; } /** * @notice Amount of remaining tokens spender is allowed to transfer on * behalf of the token owner * @param owner Token owner's address * @param spender Spender's address * @return Allowance amount */ function allowance(address owner, address spender) external override view returns (uint256) { return allowed[owner][spender]; } /** * @dev Get totalSupply of token */ function totalSupply() external override view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * @param account address The account */ function balanceOf(address account) external override view returns (uint256) { return balances[account]; } /** * @notice Set spender's allowance over the caller's tokens to be a given * value. * @param spender Spender's address * @param value Allowance amount * @return True if successful */ function approve(address spender, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Internal function to set allowance * @param owner Token owner's address * @param spender Spender's address * @param value Allowance amount */ function _approve( address owner, address spender, uint256 value ) internal override { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @notice Transfer tokens by spending allowance * @param from Payer's address * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transferFrom( address from, address to, uint256 value ) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(from) notBlacklisted(to) returns (bool) { require( value <= allowed[from][msg.sender], "ERC20: transfer amount exceeds allowance" ); _transfer(from, to, value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); return true; } /** * @notice Transfer tokens from the caller * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transfer(address to, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(to) returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @notice Internal function to process transfers * @param from Payer's address * @param to Payee's address * @param value Transfer amount */ function _transfer( address from, address to, uint256 value ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require( value <= balances[from], "ERC20: transfer amount exceeds balance" ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Function to add/update a new minter * @param minter The address of the minter * @param minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) external whenNotPaused onlyMasterMinter returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * @param minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) external onlyMasterMinter returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter's account balance * @param _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) { uint256 balance = balances[msg.sender]; require(_amount > 0, "FiatToken: burn amount not greater than 0"); require(balance >= _amount, "FiatToken: burn amount exceeds balance"); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) external onlyOwner { require( _newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } } // File: @openzeppelin/contracts/utils/Address.sol // License: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // License: MIT pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/v1.1/Rescuable.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; contract Rescuable is Ownable { using SafeERC20 for IERC20; address private _rescuer; event RescuerChanged(address indexed newRescuer); /** * @notice Returns current rescuer * @return Rescuer's address */ function rescuer() external view returns (address) { return _rescuer; } /** * @notice Revert if called by any account other than the rescuer. */ modifier onlyRescuer() { require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer"); _; } /** * @notice Rescue ERC20 tokens locked up in this contract. * @param tokenContract ERC20 token contract address * @param to Recipient address * @param amount Amount to withdraw */ function rescueERC20( IERC20 tokenContract, address to, uint256 amount ) external onlyRescuer { tokenContract.safeTransfer(to, amount); } /** * @notice Assign the rescuer role to a given address. * @param newRescuer New rescuer's address */ function updateRescuer(address newRescuer) external onlyOwner { require( newRescuer != address(0), "Rescuable: new rescuer is the zero address" ); _rescuer = newRescuer; emit RescuerChanged(newRescuer); } } // File: contracts/v1.1/FiatTokenV1_1.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title FiatTokenV1_1 * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1_1 is FiatTokenV1, Rescuable { } // File: contracts/v2/AbstractFiatTokenV2.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 { function _increaseAllowance( address owner, address spender, uint256 increment ) internal virtual; function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal virtual; } // File: contracts/util/ECRecover.sol /** * License: MIT * * Copyright (c) 2016-2019 zOS Global Limited * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library ECRecover { /** * @notice Recover signer's address from a signed message * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol * Modifications: Accept v, r, and s as separate arguments * @param digest Keccak-256 hash digest of the signed message * @param v v of the signature * @param r r of the signature * @param s s of the signature * @return Signer address */ function recover( bytes32 digest, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { revert("ECRecover: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECRecover: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(digest, v, r, s); require(signer != address(0), "ECRecover: invalid signature"); return signer; } } // File: contracts/util/EIP712.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title EIP712 * @notice A library that provides EIP712 helper functions */ library EIP712 { /** * @notice Make EIP712 domain separator * @param name Contract name * @param version Contract version * @return Domain separator */ function makeDomainSeparator(string memory name, string memory version) internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return keccak256( abi.encode( 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, // = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /** * @notice Recover signer's address from a EIP712 signature * @param domainSeparator Domain separator * @param v v of the signature * @param r r of the signature * @param s s of the signature * @param typeHashAndData Type hash concatenated with data * @return Signer's address */ function recover( bytes32 domainSeparator, uint8 v, bytes32 r, bytes32 s, bytes memory typeHashAndData ) internal pure returns (address) { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256(typeHashAndData) ) ); return ECRecover.recover(digest, v, r, s); } } // File: contracts/v2/EIP712Domain.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title EIP712 Domain */ contract EIP712Domain { /** * @dev EIP712 Domain Separator */ bytes32 public DOMAIN_SEPARATOR; } // File: contracts/v2/GasAbstraction.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title Gas Abstraction * @notice Provide internal implementation for gas-abstracted transfers and * approvals * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ abstract contract GasAbstraction is AbstractFiatTokenV2, EIP712Domain { bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // = keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant APPROVE_WITH_AUTHORIZATION_TYPEHASH = 0x808c10407a796f3ef2c7ea38c0638ea9d2b8a1c63e3ca9e1f56ce84ae59df73c; // = keccak256("ApproveWithAuthorization(address owner,address spender,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0x424222bb050a1f7f14017232a5671f2680a2d3420f504bd565cf03035c53198a; // = keccak256("IncreaseAllowanceWithAuthorization(address owner,address spender,uint256 increment,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0xb70559e94cbda91958ebec07f9b65b3b490097c8d25c8dacd71105df1015b6d8; // = keccak256("DecreaseAllowanceWithAuthorization(address owner,address spender,uint256 decrement,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; // = keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") enum AuthorizationState { Unused, Used, Canceled } /** * @dev authorizer address => nonce => authorization state */ mapping(address => mapping(bytes32 => AuthorizationState)) private _authorizationStates; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled( address indexed authorizer, bytes32 indexed nonce ); /** * @notice Returns the state of an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return Authorization state */ function authorizationState(address authorizer, bytes32 nonce) external view returns (AuthorizationState) { return _authorizationStates[authorizer][nonce]; } /** * @notice Verify a signed transfer authorization and execute if valid * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Verify a signed authorization for an increase in the allowance * granted to the spender and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param increment Amount of increase in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _increaseAllowanceWithAuthorization( address owner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(owner, nonce, validAfter, validBefore); bytes memory data = abi.encode( INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH, owner, spender, increment, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(owner, nonce); _increaseAllowance(owner, spender, increment); } /** * @notice Verify a signed authorization for a decrease in the allowance * granted to the spender and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param decrement Amount of decrease in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _decreaseAllowanceWithAuthorization( address owner, address spender, uint256 decrement, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(owner, nonce, validAfter, validBefore); bytes memory data = abi.encode( DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH, owner, spender, decrement, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(owner, nonce); _decreaseAllowance(owner, spender, decrement); } /** * @notice Verify a signed approval authorization and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _approveWithAuthorization( address owner, address spender, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(owner, nonce, validAfter, validBefore); bytes memory data = abi.encode( APPROVE_WITH_AUTHORIZATION_TYPEHASH, owner, spender, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(owner, nonce); _approve(owner, spender, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode( CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer, "FiatTokenV2: invalid signature" ); _authorizationStates[authorizer][nonce] = AuthorizationState.Canceled; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( _authorizationStates[authorizer][nonce] == AuthorizationState.Unused, "FiatTokenV2: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require( now > validAfter, "FiatTokenV2: authorization is not yet valid" ); require(now < validBefore, "FiatTokenV2: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { _authorizationStates[authorizer][nonce] = AuthorizationState.Used; emit AuthorizationUsed(authorizer, nonce); } } // File: contracts/v2/Permit.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title Permit * @notice An alternative to approveWithAuthorization, provided for * compatibility with the draft EIP2612 proposed by Uniswap. * @dev Differences: * - Uses sequential nonce, which restricts transaction submission to one at a * time, or else it will revert * - Has deadline (= validBefore - 1) but does not have validAfter * - Doesn't have a way to change allowance atomically to prevent ERC20 multiple * withdrawal attacks */ abstract contract Permit is AbstractFiatTokenV2, EIP712Domain { bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; // = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") mapping(address => uint256) private _permitNonces; /** * @notice Nonces for permit * @param owner Token owner's address (Authorizer) * @return Next nonce */ function nonces(address owner) external view returns (uint256) { return _permitNonces[owner]; } /** * @notice Verify a signed approval permit and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline The time at which this expires (unix time) * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { require(deadline >= now, "FiatTokenV2: permit is expired"); bytes memory data = abi.encode( PERMIT_TYPEHASH, owner, spender, value, _permitNonces[owner]++, deadline ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner, "FiatTokenV2: invalid signature" ); _approve(owner, spender, value); } } // File: contracts/v2/FiatTokenV2.sol /** * License: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title FiatToken V2 * @notice ERC20 Token backed by fiat reserves, version 2 */ contract FiatTokenV2 is FiatTokenV1_1, GasAbstraction, Permit { bool internal _initializedV2; /** * @notice Initialize V2 contract * @dev When upgrading to V2, this function must also be invoked by using * upgradeToAndCall instead of upgradeTo, or by calling both from a contract * in a single transaction. * @param newName New token name */ function initializeV2(string calldata newName) external { require( !_initializedV2, "FiatTokenV2: contract is already initialized" ); name = newName; DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(newName, "2"); _initializedV2 = true; } /** * @notice Increase the allowance by a given increment * @param spender Spender's address * @param increment Amount of increase in allowance * @return True if successful */ function increaseAllowance(address spender, uint256 increment) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _increaseAllowance(msg.sender, spender, increment); return true; } /** * @notice Decrease the allowance by a given decrement * @param spender Spender's address * @param decrement Amount of decrease in allowance * @return True if successful */ function decreaseAllowance(address spender, uint256 decrement) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _decreaseAllowance(msg.sender, spender, decrement); return true; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) { _transferWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Update allowance with a signed authorization * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function approveWithAuthorization( address owner, address spender, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) { _approveWithAuthorization( owner, spender, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Increase allowance with a signed authorization * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param increment Amount of increase in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function increaseAllowanceWithAuthorization( address owner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) { _increaseAllowanceWithAuthorization( owner, spender, increment, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Decrease allowance with a signed authorization * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param decrement Amount of decrease in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function decreaseAllowanceWithAuthorization( address owner, address spender, uint256 decrement, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) { _decreaseAllowanceWithAuthorization( owner, spender, decrement, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Attempt to cancel an authorization * @dev Works only if the authorization is not yet used. * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused { _cancelAuthorization(authorizer, nonce, v, r, s); } /** * @notice Update allowance with a signed permit * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline Expiration time, seconds since the epoch * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) { _permit(owner, spender, value, deadline, v, r, s); } /** * @notice Internal function to increase the allowance by a given increment * @param owner Token owner's address * @param spender Spender's address * @param increment Amount of increase */ function _increaseAllowance( address owner, address spender, uint256 increment ) internal override { _approve(owner, spender, allowed[owner][spender].add(increment)); } /** * @notice Internal function to decrease the allowance by a given decrement * @param owner Token owner's address * @param spender Spender's address * @param decrement Amount of decrease */ function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal override { _approve( owner, spender, allowed[owner][spender].sub( decrement, "ERC20: decreased allowance below zero" ) ); } }
Check that an authorization is unused authorizer Authorizer's address nonce Nonce of the authorization/
function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( _authorizationStates[authorizer][nonce] == AuthorizationState.Unused, "FiatTokenV2: authorization is used or canceled" ); }
529,587
./full_match/1/0x9bC228711706db212ED2BC12d9dC1643cf304EEA/sources/src/ethereum/RewardsDistributorV2.sol
Verify the merkle proof
function _claim( address _token, uint256 _index, address _account, uint256 _amount, bytes32[] calldata _merkleProof ) internal { if (merkleRoot[_token] == 0) revert ClaimingIsPaused(); if (isClaimed(_token, _index)) revert AlreadyClaimed(); bytes32 node = keccak256(bytes.concat(keccak256(abi.encode(_index, _account, _amount)))); if (!MerkleProofUpgradeable.verify(_merkleProof, merkleRoot[_token], node)) revert InvalidMerkleProof(); _setClaimed(_token, _index); IERC20Upgradeable(_token).safeTransfer(_account, _amount); emit RewardClaimed(_token, _account, _index, _amount, claimPeriod[_token]); }
8,424,033
./partial_match/8453/0xc7b006f084Ca79334DB41fE216D3195870FAc026/sources/DUCKRouter.sol
performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'DUCKLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } }
16,760,438
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./Uniswap.sol"; import "./IUniMexFactory.sol"; import "hardhat/console.sol"; interface IUniMexStaking { function distribute(uint256 _amount) external; } interface IUniMexPool { function borrow(uint256 _amount) external; function distribute(uint256 _amount) external; function repay(uint256 _amount) external returns (bool); } contract UniMexMargin is Ownable, AccessControl, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint32; using SafeERC20 for IERC20; bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE"); address private WETH_ADDRESS; IERC20 public WETH; uint256 public constant MAG = 1e18; uint256 public constant LIQUIDATION_MARGIN = 1.1e18; //11% uint256 public thresholdGasPrice = 3e8; //gas price in wei used to calculate bonuses for liquidation, sl, tp uint32 public borrowInterestPercentScaled = 100; //10% uint256 public constant YEAR = 31536000; uint256 public positionNonce = 0; bool public paused = false; uint256 public amountThresholds; struct Position { uint256 owed; uint256 input; uint256 commitment; address token; bool isShort; uint32 startTimestamp; uint32 borrowInterest; address owner; uint32 stopLossPercent; uint32 takeProfitPercent; } struct Limit { uint256 amount; uint256 minimalSwapAmount; address token; bool isShort; uint32 validBefore; uint32 leverageScaled; address owner; uint32 takeProfitPercent; uint32 stopLossPercent; uint256 escrowAmount; } mapping(bytes32 => Position) public positionInfo; mapping(bytes32 => Limit) public limitOrders; mapping(address => uint256) public balanceOf; mapping(address => uint256) public escrow; IUniMexStaking public staking; IUniMexFactory public unimex_factory; IUniswapV2Factory public uniswap_factory; IUniswapV2Router02 public uniswap_router; event OnClosePosition( bytes32 indexed positionId, address token, address indexed owner, uint256 owed, uint256 input, uint256 commitment, uint32 startTimestamp, bool isShort, uint256 borrowInterest, uint256 liquidationBonus, //amount that went to liquidator when position was liquidated. 0 if position was closed uint256 scaledCloseRate // weth/token multiplied by 1e18 ); event OnOpenPosition( address indexed sender, bytes32 positionId, bool isShort, address indexed token, uint256 scaledLeverage ); event OnAddCommitment( bytes32 indexed positionId, uint256 amount ); event OnLimitOrder( bytes32 indexed limitOrderId, address indexed owner, address token, uint256 amount, uint256 minimalSwapAmount, uint256 leverageScaled, uint256 validBefore, uint256 escrowAmount, uint32 takeProfitPercent, uint32 stopLossPercent, bool isShort ); event OnLimitOrderCancelled( bytes32 indexed limitOrderId ); event OnLimitOrderCompleted( bytes32 indexed limitOrderId, bytes32 positionId ); event OnTakeProfit( bytes32 indexed positionId, uint256 positionInput, uint256 swapAmount, address token, bool isShort ); event OnStopLoss( bytes32 indexed positionId, uint256 positionInput, uint256 swapAmount, address token, bool isShort ); //to prevent flashloans modifier isHuman() { require(msg.sender == tx.origin); _; } constructor( address _staking, address _factory, address _weth, address _uniswap_factory, address _uniswap_router ) public { staking = IUniMexStaking(_staking); unimex_factory = IUniMexFactory(_factory); WETH_ADDRESS = _weth; WETH = IERC20(_weth); uniswap_factory = IUniswapV2Factory(_uniswap_factory); uniswap_router = IUniswapV2Router02(_uniswap_router); // Grant the contract deployer the default admin role: it will be able // to grant and revoke any roles _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); amountThresholds = 275; } function deposit(uint256 _amount) public { WETH.safeTransferFrom(msg.sender, address(this), _amount); balanceOf[msg.sender] = balanceOf[msg.sender].add(_amount); } function withdraw(uint256 _amount) public { require(balanceOf[msg.sender] >= _amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_amount); WETH.safeTransfer(msg.sender, _amount); } function calculateBorrowInterest(bytes32 positionId) public view returns (uint256) { Position storage position = positionInfo[positionId]; uint256 loanTime = block.timestamp.sub(position.startTimestamp); return position.owed.mul(loanTime).mul(position.borrowInterest).div(1000).div(YEAR); } function openShortPosition(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount) public isHuman { uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, 0, 0]; _openPosition(msg.sender, token, true, values); } function openLongPosition(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount) public isHuman { uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, 0, 0]; _openPosition(msg.sender, token, false, values); } function openShortPositionWithSlTp(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount, uint256 takeProfitPercent, uint256 stopLossPercent) public isHuman { uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, takeProfitPercent, stopLossPercent]; _openPosition(msg.sender, token, true, values); } function openLongPositionWithSlTp(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount, uint256 takeProfitPercent, uint256 stopLossPercent) public isHuman { uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, takeProfitPercent, stopLossPercent]; _openPosition(msg.sender, token, false, values); } /** * values[0] amount * values[1] scaledLeverage * values[2] minimalSwapAmount * values[3] takeProfitPercent * values[4] stopLossPercent */ function _openPosition(address owner, address token, bool isShort, uint256[5] memory values) private nonReentrant returns (bytes32) { require(!paused, "PAUSED"); require(values[0] > 0, "AMOUNT_ZERO"); require(values[4] < 1e6, "STOPLOSS EXCEEDS MAX"); address pool = unimex_factory.getPool(address(isShort ? IERC20(token) : WETH)); require(pool != address(0), "POOL_DOES_NOT_EXIST"); require(values[1] <= unimex_factory.getMaxLeverage(token).mul(MAG), "LEVERAGE_EXCEEDS_MAX"); require(checkPositionAmount(token, values[0], values[1]), "NOT_ENOUGH_UNISWAP_LIQUIDITY"); uint256 amountInWeth = isShort ? calculateConvertedValue(token, WETH_ADDRESS, values[0]) : values[0]; uint256 commitment = getCommitment(amountInWeth, values[1]); uint256 commitmentWithLb = commitment.add(calculateAutoCloseBonus()); require(balanceOf[owner] >= commitmentWithLb, "NO_BALANCE"); IUniMexPool(pool).borrow(values[0]); uint256 swap; { (address baseToken, address quoteToken) = isShort ? (token, WETH_ADDRESS) : (WETH_ADDRESS, token); swap = swapTokens(baseToken, quoteToken, values[0]); require(swap >= values[2], "INSUFFICIENT_SWAP"); } uint256 fees = (swap.mul(4)).div(1000); swap = swap.sub(fees); if(!isShort) { fees = swapTokens(token, WETH_ADDRESS, fees); // convert fees to ETH } transferFees(fees, pool); transferUserToEscrow(owner, owner, commitmentWithLb); positionNonce = positionNonce + 1; //possible overflow is ok bytes32 positionId = getPositionId( owner, token, values[0], values[1], positionNonce ); Position memory position = Position({ owed: values[0], input: swap, commitment: commitmentWithLb, token: token, isShort: isShort, startTimestamp: uint32(block.timestamp), owner: owner, borrowInterest: borrowInterestPercentScaled, takeProfitPercent: uint32(values[3]), stopLossPercent: uint32(values[4]) }); positionInfo[positionId] = position; emit OnOpenPosition(owner, positionId, isShort, token, values[1]); if(position.takeProfitPercent > 0) { emit OnTakeProfit(positionId, swap, position.takeProfitPercent, token, isShort); } if(position.stopLossPercent > 0) { emit OnStopLoss(positionId, swap, position.stopLossPercent, token, isShort); } return positionId; } /** * @dev add additional commitment to an opened position. The amount * must be initially approved * @param positionId id of the position to add commitment * @param amount the amount to add to commitment */ function addCommitmentToPosition(bytes32 positionId, uint256 amount) public { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); position.commitment = position.commitment.add(amount); WETH.safeTransferFrom(msg.sender, address(this), amount); escrow[position.owner] = escrow[position.owner].add(amount); emit OnAddCommitment(positionId, amount); } /** * @dev allows anyone to close position if it's loss exceeds threshold */ function setStopLoss(bytes32 positionId, uint32 percentAmount) public { require(percentAmount < 1e6, "STOPLOSS EXCEEDS MAX"); Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); require(msg.sender == position.owner, "NOT_OWNER"); position.stopLossPercent = percentAmount; emit OnStopLoss(positionId, position.input, percentAmount, position.token, position.isShort); } /** * @dev allows anyone to close position if it's profit exceeds threshold */ function setTakeProfit(bytes32 positionId, uint32 percentAmount) public { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); require(msg.sender == position.owner, "NOT_OWNER"); position.takeProfitPercent = percentAmount; emit OnTakeProfit(positionId, position.input, percentAmount, position.token, position.isShort); } function autoClose(bytes32 positionId) public isHuman { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); //check constraints (address baseToken, address quoteToken) = position.isShort ? (WETH_ADDRESS, position.token) : (position.token, WETH_ADDRESS); uint256 swapAmount = calculateConvertedValue(baseToken, quoteToken, position.input); uint256 hundredPercent = 1e6; require((position.takeProfitPercent != 0 && position.owed.mul(hundredPercent.add(position.takeProfitPercent)).div(hundredPercent) <= swapAmount) || (position.stopLossPercent != 0 && position.owed.mul(hundredPercent.sub(position.stopLossPercent)).div(hundredPercent) >= swapAmount), "SL_OR_TP_UNAVAILABLE"); //withdraw bonus from position commitment uint256 closeBonus = calculateAutoCloseBonus(); position.commitment = position.commitment.sub(closeBonus); WETH.safeTransfer(msg.sender, closeBonus); transferEscrowToUser(position.owner, address(0), closeBonus); _closePosition(positionId, position, 0); } function calculateAutoOpenBonus() public view returns(uint256) { return thresholdGasPrice.mul(510000); } function calculateAutoCloseBonus() public view returns(uint256) { return thresholdGasPrice.mul(270000); } /** * @dev opens position that can be opened at a specific price */ function openLimitOrder(address token, bool isShort, uint256 amount, uint256 minimalSwapAmount, uint256 leverageScaled, uint32 validBefore, uint32 takeProfitPercent, uint32 stopLossPercent) public { require(!paused, "PAUSED"); require(stopLossPercent < 1e6, "STOPLOSS EXCEEDS MAX"); require(validBefore > block.timestamp, "INCORRECT_EXP_DATE"); uint256[3] memory values256 = [amount, minimalSwapAmount, leverageScaled]; uint32[3] memory values32 = [validBefore, takeProfitPercent, stopLossPercent]; _openLimitOrder(token, isShort, values256, values32); } /** * @dev values256[0] - amount * values256[1] - minimal swap amount * values256[2] - scaled leverage * values32[0] - valid before * values32[1] - take profit percent * values32[2] - stop loss percent */ function _openLimitOrder(address token, bool isShort, uint256[3] memory values256, uint32[3] memory values) private { uint256 escrowAmount; //stack depth optimization { uint256 commitment = isShort ? getCommitment(values256[1], values256[2]) : getCommitment(values256[0], values256[2]); escrowAmount = commitment.add(calculateAutoOpenBonus()).add(calculateAutoCloseBonus()); require(balanceOf[msg.sender] >= escrowAmount, "INSUFFICIENT_BALANCE"); transferUserToEscrow(msg.sender, msg.sender, escrowAmount); } bytes32 limitOrderId = _getLimitOrderId(token, values256[0], values256[1], values256[2], values[0], msg.sender, isShort); Limit memory limitOrder = Limit({ token: token, amount: values256[0], minimalSwapAmount: values256[1], leverageScaled: uint32(values256[2].div(1e14)), validBefore: values[0], owner: msg.sender, escrowAmount: escrowAmount, isShort: isShort, takeProfitPercent: values[1], stopLossPercent: values[2] }); limitOrders[limitOrderId] = limitOrder; emitLimitOrderEvent(limitOrderId, token, values256, values, escrowAmount, isShort); } function emitLimitOrderEvent(bytes32 limitOrderId, address token, uint256[3] memory values256, uint32[3] memory values, uint256 escrowAmount, bool isShort) private { emit OnLimitOrder(limitOrderId, msg.sender, token, values256[0], values[1], values256[2], values[0], escrowAmount, values[1], values[2], isShort); } function cancelLimitOrder(bytes32 limitOrderId) public { Limit storage limitOrder = limitOrders[limitOrderId]; require(limitOrder.owner == msg.sender, "NOT_OWNER"); transferEscrowToUser(limitOrder.owner, limitOrder.owner, limitOrder.escrowAmount); delete limitOrders[limitOrderId]; emit OnLimitOrderCancelled(limitOrderId); } function autoOpen(bytes32 limitOrderId) public isHuman { //get limit order Limit storage limitOrder = limitOrders[limitOrderId]; require(limitOrder.owner != address(0), "NO_ORDER"); require(limitOrder.validBefore >= uint32(block.timestamp), "EXPIRED"); //check open rate (address baseToken, address quoteToken) = limitOrder.isShort ? (limitOrder.token, WETH_ADDRESS) : (WETH_ADDRESS, limitOrder.token); uint256 swapAmount = calculateConvertedValue(baseToken, quoteToken, limitOrder.amount); require(swapAmount >= limitOrder.minimalSwapAmount, "LIMIT_NOT_SATISFIED"); uint256 openBonus = calculateAutoOpenBonus(); //transfer bonus from escrow to caller WETH.transfer(msg.sender, openBonus); transferEscrowToUser(limitOrder.owner, limitOrder.owner, limitOrder.escrowAmount.sub(openBonus)); transferEscrowToUser(limitOrder.owner, address(0), openBonus); //open position for user uint256[5] memory values = [limitOrder.amount, uint256(limitOrder.leverageScaled.mul(1e14)), limitOrder.minimalSwapAmount, uint256(limitOrder.takeProfitPercent), uint256(limitOrder.stopLossPercent)]; bytes32 positionId = _openPosition(limitOrder.owner, limitOrder.token, limitOrder.isShort, values); //delete order id delete limitOrders[limitOrderId]; emit OnLimitOrderCompleted(limitOrderId, positionId); } function _getLimitOrderId(address token, uint256 amount, uint256 minSwapAmount, uint256 scaledLeverage, uint256 validBefore, address owner, bool isShort) private pure returns (bytes32) { return keccak256(abi.encodePacked(token, amount, minSwapAmount, scaledLeverage, validBefore, owner, isShort)); } function _checkPositionIsOpen(Position storage position) private view { require(position.owner != address(0), "NO_OPEN_POSITION"); } function closePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); require(msg.sender == position.owner, "BORROWER_ONLY"); _closePosition(positionId, position, minimalSwapAmount); } function _closePosition(bytes32 positionId, Position storage position, uint256 minimalSwapAmount) private nonReentrant{ uint256 scaledRate; if(position.isShort) { scaledRate = _closeShort(positionId, position, minimalSwapAmount); }else{ scaledRate = _closeLong(positionId, position, minimalSwapAmount); } deletePosition(positionId, position, 0, scaledRate); } function _closeShort(bytes32 positionId, Position storage position, uint256 minimalSwapAmount) private returns (uint256){ uint256 input = position.input; uint256 owed = position.owed; uint256 commitment = position.commitment; address pool = unimex_factory.getPool(position.token); uint256 poolInterestInTokens = calculateBorrowInterest(positionId); uint256 swap = swapTokens(WETH_ADDRESS, position.token, input); require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP"); uint256 scaledRate = calculateScaledRate(input, swap); require(swap >= owed.add(poolInterestInTokens).mul(input).div(input.add(commitment)), "LIQUIDATE_ONLY"); bool isProfit = owed < swap; uint256 amount; uint256 fees = poolInterestInTokens > 0 ? calculateConvertedValue(position.token, address(WETH), poolInterestInTokens) : 0; if(isProfit) { uint256 profitInTokens = swap.sub(owed); amount = swapTokens(position.token, WETH_ADDRESS, profitInTokens); //profit in eth } else { uint256 commitmentInTokens = swapTokens(WETH_ADDRESS, position.token, commitment); uint256 remainder = owed.sub(swap); require(commitmentInTokens >= remainder, "LIQUIDATE_ONLY"); amount = swapTokens(position.token, WETH_ADDRESS, commitmentInTokens.sub(remainder)); //return to user's balance } if(isProfit) { if(amount >= fees) { transferEscrowToUser(position.owner, position.owner, commitment); transferToUser(position.owner, amount.sub(fees)); } else { uint256 remainder = fees.sub(amount); transferEscrowToUser(position.owner, position.owner, commitment.sub(remainder)); transferEscrowToUser(position.owner, address(0), remainder); } } else { require(amount >= fees, "LIQUIDATE_ONLY"); //safety check transferEscrowToUser(position.owner, address(0x0), commitment); transferToUser(position.owner, amount.sub(fees)); } transferFees(fees, pool); transferToPool(pool, position.token, owed); return scaledRate; } function _closeLong(bytes32 positionId, Position storage position, uint256 minimalSwapAmount) private returns (uint256){ uint256 input = position.input; uint256 owed = position.owed; address pool = unimex_factory.getPool(WETH_ADDRESS); uint256 fees = calculateBorrowInterest(positionId); uint256 swap = swapTokens(position.token, WETH_ADDRESS, input); require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP"); uint256 scaledRate = calculateScaledRate(swap, input); require(swap.add(position.commitment) >= owed.add(fees), "LIQUIDATE_ONLY"); uint256 commitment = position.commitment; bool isProfit = swap >= owed; uint256 amount = isProfit ? swap.sub(owed) : commitment.sub(owed.sub(swap)); transferToPool(pool, WETH_ADDRESS, owed); transferFees(fees, pool); transferEscrowToUser(position.owner, isProfit ? position.owner : address(0x0), commitment); transferToUser(position.owner, amount.sub(fees)); return scaledRate; } /** * @dev helper function, indicates when a position can be liquidated. * Liquidation threshold is when position input plus commitment can be converted to 110% of owed tokens */ function canLiquidate(bytes32 positionId) public view returns(bool) { Position storage position = positionInfo[positionId]; uint256 liquidationBonus = calculateAutoCloseBonus(); uint256 canReturn; if(position.isShort) { uint256 positionBalance = position.input.add(position.commitment); uint256 valueToConvert = positionBalance < liquidationBonus ? 0 : positionBalance.sub(liquidationBonus); canReturn = calculateConvertedValue(WETH_ADDRESS, position.token, valueToConvert); } else { uint256 canReturnOverall = calculateConvertedValue(position.token, WETH_ADDRESS, position.input) .add(position.commitment); canReturn = canReturnOverall < liquidationBonus ? 0 : canReturnOverall.sub(liquidationBonus); } uint256 poolInterest = calculateBorrowInterest(positionId); return canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG); } /** * @dev Liquidates position and sends a liquidation bonus from user's commitment to a caller. * can only be called from account that has the LIQUIDATOR role */ function liquidatePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman nonReentrant { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); uint256 canReturn; uint256 poolInterest = calculateBorrowInterest(positionId); uint256 liquidationBonus = calculateAutoCloseBonus(); uint256 liquidatorBonus; uint256 scaledRate; if(position.isShort) { uint256 positionBalance = position.input.add(position.commitment); uint256 valueToConvert; (valueToConvert, liquidatorBonus) = _safeSubtract(positionBalance, liquidationBonus); canReturn = swapTokens(WETH_ADDRESS, position.token, valueToConvert); require(canReturn >= minimalSwapAmount, "INSUFFICIENT_SWAP"); scaledRate = calculateScaledRate(valueToConvert, canReturn); } else { uint256 swap = swapTokens(position.token, WETH_ADDRESS, position.input); require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP"); scaledRate = calculateScaledRate(swap, position.input); uint256 canReturnOverall = swap.add(position.commitment); (canReturn, liquidatorBonus) = _safeSubtract(canReturnOverall, liquidationBonus); } require(canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG), "CANNOT_LIQUIDATE"); _liquidate(position, canReturn, poolInterest); transferEscrowToUser(position.owner, address(0x0), position.commitment); WETH.safeTransfer(msg.sender, liquidatorBonus); deletePosition(positionId, position, liquidatorBonus, scaledRate); } function _liquidate(Position memory position, uint256 canReturn, uint256 fees) private { address baseToken = position.isShort ? position.token : WETH_ADDRESS; address pool = unimex_factory.getPool(baseToken); if(canReturn > position.owed) { transferToPool(pool, baseToken, position.owed); uint256 remainder = canReturn.sub(position.owed); if(remainder > fees) { //can pay fees completely if(position.isShort) { remainder = swapTokens(position.token, WETH_ADDRESS, remainder); if(fees > 0) { //with fees == 0 calculation is reverted with "UV2: insufficient input amount" fees = calculateConvertedValue(position.token, WETH_ADDRESS, fees); if(fees > remainder) { //safety check fees = remainder; } } } transferFees(fees, pool); transferToUser(position.owner, remainder.sub(fees)); } else { //all is left is for fees if(position.isShort) { //convert remainder to weth remainder = swapTokens(position.token, WETH_ADDRESS, canReturn.sub(position.owed)); } transferFees(remainder, pool); } } else { //return to pool all that's left transferToPool(pool, baseToken, canReturn); } } function setStaking(address _staking) external onlyOwner { require(_staking != address(0)); staking = IUniMexStaking(_staking); } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner public { paused = true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner public { paused = false; } function setThresholdGasPrice(uint256 gasPrice) public { require(hasRole(LIQUIDATOR_ROLE, msg.sender), "NOT_LIQUIDATOR"); thresholdGasPrice = gasPrice; } /** * @dev set interest rate for tokens owed from pools. Scaled to 10 (e.g. 150 is 15%) */ function setBorrowPercent(uint32 _newPercentScaled) external onlyOwner { borrowInterestPercentScaled = _newPercentScaled; } function calculateScaledRate(uint256 wethAmount, uint256 tokenAmount) private pure returns (uint256 scaledRate) { if(tokenAmount == 0) { return 0; } return wethAmount.mul(MAG).div(tokenAmount); } function transferUserToEscrow(address from, address to, uint256 amount) private { require(balanceOf[from] >= amount); balanceOf[from] = balanceOf[from].sub(amount); escrow[to] = escrow[to].add(amount); } function transferEscrowToUser(address from, address to, uint256 amount) private { require(escrow[from] >= amount); escrow[from] = escrow[from].sub(amount); balanceOf[to] = balanceOf[to].add(amount); } function transferToUser(address to, uint256 amount) private { balanceOf[to] = balanceOf[to].add(amount); } function getPositionId( address maker, address token, uint256 amount, uint256 leverage, uint256 nonce ) private pure returns (bytes32 positionId) { //date acts as a nonce positionId = keccak256( abi.encodePacked(maker, token, amount, leverage, nonce) ); } function calculateConvertedValue(address baseToken, address quoteToken, uint256 amount) private view returns (uint256) { address token0; address token1; (token0, token1) = UniswapV2Library.sortTokens(baseToken, quoteToken); IUniswapV2Pair pair = IUniswapV2Pair(uniswap_factory.getPair(token0, token1)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 value; if (token1 == baseToken) { value = UniswapV2Library.getAmountOut(amount, reserve1, reserve0); } else { value = UniswapV2Library.getAmountOut(amount, reserve0, reserve1); } return value; } function swapTokens(address baseToken, address quoteToken, uint256 input) private returns (uint256 swap) { if(input == 0) { return 0; } IERC20(baseToken).approve(address(uniswap_router), input); address[] memory path = new address[](2); path[0] = baseToken; path[1] = quoteToken; uint256 balanceBefore = IERC20(quoteToken).balanceOf(address(this)); IUniswapV2Router02(uniswap_router).swapExactTokensForTokensSupportingFeeOnTransferTokens( input, 0, //checks are done after swap in caller functions path, address(this), block.timestamp ); uint256 balanceAfter = IERC20(quoteToken).balanceOf(address(this)); swap = balanceAfter.sub(balanceBefore); } function getCommitment(uint256 _amount, uint256 scaledLeverage) private pure returns (uint256 commitment) { commitment = (_amount.mul(MAG)).div(scaledLeverage); } function transferFees(uint256 fees, address pool) private { uint256 halfFees = fees.div(2); // Pool fees WETH.approve(pool, halfFees); IUniMexPool(pool).distribute(halfFees); // Staking Fees WETH.approve(address(staking), fees.sub(halfFees)); staking.distribute(fees.sub(halfFees)); } function transferToPool(address pool, address token, uint256 amount) private { IERC20(token).approve(pool, amount); IUniMexPool(pool).repay(amount); } function _safeSubtract(uint256 from, uint256 amount) private pure returns (uint256 remainder, uint256 subtractedAmount) { if(from < amount) { remainder = 0; subtractedAmount = from; } else { remainder = from.sub(amount); subtractedAmount = amount; } } function setAmountThresholds(uint32 leverage5) public onlyOwner { amountThresholds = leverage5; } function checkPositionAmount(address token, uint256 amount, uint256 leverageScaled) public view returns (bool) { if(leverageScaled <= 1e18) { return true; } address token0; address token1; (token0, token1) = UniswapV2Library.sortTokens(token, WETH_ADDRESS); IUniswapV2Pair pair = IUniswapV2Pair(uniswap_factory.getPair(token0, token1)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 tokenLiquidity = token0 == token ? reserve0 : reserve1; if (leverageScaled <= 2e18) { return amount < tokenLiquidity.mul(amountThresholds).mul(1109).div(1000).div(1e4); } else { return amount < tokenLiquidity.mul(amountThresholds).div(1e4); } } function deletePosition(bytes32 positionId, Position storage position, uint256 liquidatedAmount, uint256 scaledRate) private { emit OnClosePosition( positionId, position.token, position.owner, position.owed, position.input, position.commitment, position.startTimestamp, position.isShort, position.borrowInterest, liquidatedAmount, scaledRate ); delete positionInfo[positionId]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IUniswapV2Pair { function getReserves() external view returns (uint112 r0, uint112 r1, uint32 blockTimestampLast); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } interface IUniswapV2Factory { function getPair(address a, address b) external view returns (address p); } interface IUniswapV2Router02 { function WETH() external returns (address); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UV2: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UV2: ZERO_ADDRESS'); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UV2: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UV2: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface IUniMexFactory { function getPool(address) external returns(address); function getMaxLeverage(address) external returns(uint256); function allowedMargins(address) external returns (bool); function utilizationScaled(address token) external pure returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
get limit ordercheck open ratetransfer bonus from escrow to calleropen position for userdelete order id
function autoOpen(bytes32 limitOrderId) public isHuman { Limit storage limitOrder = limitOrders[limitOrderId]; require(limitOrder.owner != address(0), "NO_ORDER"); require(limitOrder.validBefore >= uint32(block.timestamp), "EXPIRED"); (address baseToken, address quoteToken) = limitOrder.isShort ? (limitOrder.token, WETH_ADDRESS) : (WETH_ADDRESS, limitOrder.token); uint256 swapAmount = calculateConvertedValue(baseToken, quoteToken, limitOrder.amount); require(swapAmount >= limitOrder.minimalSwapAmount, "LIMIT_NOT_SATISFIED"); uint256 openBonus = calculateAutoOpenBonus(); WETH.transfer(msg.sender, openBonus); transferEscrowToUser(limitOrder.owner, limitOrder.owner, limitOrder.escrowAmount.sub(openBonus)); transferEscrowToUser(limitOrder.owner, address(0), openBonus); uint256[5] memory values = [limitOrder.amount, uint256(limitOrder.leverageScaled.mul(1e14)), limitOrder.minimalSwapAmount, uint256(limitOrder.takeProfitPercent), uint256(limitOrder.stopLossPercent)]; bytes32 positionId = _openPosition(limitOrder.owner, limitOrder.token, limitOrder.isShort, values); delete limitOrders[limitOrderId]; emit OnLimitOrderCompleted(limitOrderId, positionId); }
13,657,253
./full_match/288/0x8db213bE5268a2b8B78Af08468ff1EA422073Da0/sources/contracts/pegged/OriginalTokenVault.sol
Lock original tokens to trigger mint at a remote chain's PeggedTokenBridge _token local token address _amount locked token amount _mintChainId destination chainId to mint tokens _mintAccount destination account to receive minted tokens _nonce user input to guarantee unique depositId/ len = 20 + 20 + 32 + 8 + 20 + 8 + 8 = 128
function deposit( address _token, uint256 _amount, uint64 _mintChainId, address _mintAccount, uint64 _nonce ) external nonReentrant whenNotPaused { require(_amount > minDeposit[_token], "amount too small"); require(maxDeposit[_token] == 0 || _amount <= maxDeposit[_token], "amount too large"); bytes32 depId = keccak256( abi.encodePacked(msg.sender, _token, _amount, _mintChainId, _mintAccount, _nonce, uint64(block.chainid)) ); require(records[depId] == false, "record exists"); records[depId] = true; IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); emit Deposited(depId, msg.sender, _token, _amount, _mintChainId, _mintAccount); }
7,103,603
./partial_match/1/0x33fe04039d7dC68035C689Fb1d2555A09EF9619F/sources/WishingWell.sol
check that that we have something
function withdrawWinnings() external returns (uint256){ uint256 currBal = currentWinnings(msg.sender); require(currBal > 0, "Need more than 0CLV in winnings to withdraw"); info.clv.transfer(msg.sender, currBal); info.users[msg.sender].winnings -= currBal; info.heldWinnings -= currBal; emit Withdraw(msg.sender, currBal); return currBal; }
4,484,086
pragma solidity ^0.4.13; /** * @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 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 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 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)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @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() { 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; } } ///////////////////////////////////////////////////////// //////////////// Token contract start//////////////////// ///////////////////////////////////////////////////////// contract CryptoGripInitiative is StandardToken, Ownable { string public constant name = "Crypto Grip Initiative"; string public constant symbol = "CGI"; uint public constant decimals = 18; uint public saleStartTime; uint public saleEndTime; address public tokenSaleContract; modifier onlyWhenTransferEnabled() { if (now <= saleEndTime && now >= saleStartTime) { require(msg.sender == tokenSaleContract || msg.sender == owner); } _; } modifier validDestination(address to) { require(to != address(0x0)); require(to != address(this)); _; } function CryptoGripInitiative(uint tokenTotalAmount, uint startTime, uint endTime, address admin) { // Mint all tokens. Then disable minting forever. balances[msg.sender] = tokenTotalAmount; totalSupply = tokenTotalAmount; Transfer(address(0x0), msg.sender, tokenTotalAmount); saleStartTime = startTime; saleEndTime = endTime; tokenSaleContract = msg.sender; transferOwnership(admin); // admin could drain tokens that were sent here by mistake } function transfer(address _to, uint _value) onlyWhenTransferEnabled validDestination(_to) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) onlyWhenTransferEnabled validDestination(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } event Burn(address indexed _burner, uint _value); function burn(uint _value) onlyWhenTransferEnabled returns (bool){ balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender, _value); Transfer(msg.sender, address(0x0), _value); return true; } // // save some gas by making only one contract call // function burnFrom(address _from, uint256 _value) onlyWhenTransferEnabled // returns (bool) { // assert(transferFrom(_from, msg.sender, _value)); // return burn(_value); // } function emergencyERC20Drain(ERC20 token, uint amount) onlyOwner { token.transfer(owner, amount); } } ///////////////////////////////////////////////////////// /////////////// Whitelist contract start///////////////// ///////////////////////////////////////////////////////// contract Whitelist { address public owner; address public sale; mapping (address => uint) public accepted; function Whitelist(address _owner, address _sale) { owner = _owner; sale = _sale; } function accept(address a, uint amountInWei) { assert(msg.sender == owner || msg.sender == sale); accepted[a] = amountInWei * 10 ** 18; } function setSale(address sale_) { assert(msg.sender == owner); sale = sale_; } function getCap(address _user) constant returns (uint) { uint cap = accepted[_user]; return cap; } } ///////////////////////////////////////////////////////// ///////// Contributor Approver contract start//////////// ///////////////////////////////////////////////////////// contract ContributorApprover { Whitelist public list; mapping (address => uint) public participated; uint public presaleStartTime; uint public remainingPresaleCap; uint public remainingPublicSaleCap; uint public openSaleStartTime; uint public openSaleEndTime; using SafeMath for uint; function ContributorApprover( Whitelist _whitelistContract, uint preIcoCap, uint IcoCap, uint _presaleStartTime, uint _openSaleStartTime, uint _openSaleEndTime) { list = _whitelistContract; openSaleStartTime = _openSaleStartTime; openSaleEndTime = _openSaleEndTime; presaleStartTime = _presaleStartTime; remainingPresaleCap = preIcoCap * 10 ** 18; remainingPublicSaleCap = IcoCap * 10 ** 18; // Check that presale is earlier than opensale require(presaleStartTime < openSaleStartTime); // Check that open sale start is earlier than end require(openSaleStartTime < openSaleEndTime); } // this is a seperate function so user could query it before crowdsale starts function contributorCap(address contributor) constant returns (uint) { return list.getCap(contributor); } function eligible(address contributor, uint amountInWei) constant returns (uint) { // Presale not started yet if (now < presaleStartTime) return 0; // Both presale and public sale have ended if (now >= openSaleEndTime) return 0; // Presale if (now < openSaleStartTime) { // Presale cap limit reached if (remainingPresaleCap <= 0) { return 0; } // Get initial cap uint cap = contributorCap(contributor); // Account for already invested amount uint remainedCap = cap.sub(participated[contributor]); // Presale cap almost reached if (remainedCap > remainingPresaleCap) { remainedCap = remainingPresaleCap; } // Remaining cap is bigger than contribution if (remainedCap > amountInWei) return amountInWei; // Remaining cap is smaller than contribution else return remainedCap; } // Public sale else { // Public sale cap limit reached if (remainingPublicSaleCap <= 0) { return 0; } // Public sale cap almost reached if (amountInWei > remainingPublicSaleCap) { return remainingPublicSaleCap; } // Public sale cap is bigger than contribution else { return amountInWei; } } } function eligibleTestAndIncrement(address contributor, uint amountInWei) internal returns (uint) { uint result = eligible(contributor, amountInWei); participated[contributor] = participated[contributor].add(result); // Presale if (now < openSaleStartTime) { // Decrement presale cap remainingPresaleCap = remainingPresaleCap.sub(result); } // Publicsale else { // Decrement publicsale cap remainingPublicSaleCap = remainingPublicSaleCap.sub(result); } return result; } function saleEnded() constant returns (bool) { return now > openSaleEndTime; } function saleStarted() constant returns (bool) { return now >= presaleStartTime; } function publicSaleStarted() constant returns (bool) { return now >= openSaleStartTime; } } ///////////////////////////////////////////////////////// ///////// Token Sale contract start ///////////////////// ///////////////////////////////////////////////////////// contract CryptoGripTokenSale is ContributorApprover { uint public constant tokensPerEthPresale = 1055; uint public constant tokensPerEthPublicSale = 755; address public admin; address public gripWallet; CryptoGripInitiative public token; uint public raisedWei; bool public haltSale; function CryptoGripTokenSale(address _admin, address _gripWallet, Whitelist _whiteListContract, uint _totalTokenSupply, uint _premintedTokenSupply, uint _presaleStartTime, uint _publicSaleStartTime, uint _publicSaleEndTime, uint _presaleCap, uint _publicSaleCap) ContributorApprover(_whiteListContract, _presaleCap, _publicSaleCap, _presaleStartTime, _publicSaleStartTime, _publicSaleEndTime) { admin = _admin; gripWallet = _gripWallet; token = new CryptoGripInitiative(_totalTokenSupply * 10 ** 18, _presaleStartTime, _publicSaleEndTime, _admin); // transfer preminted tokens to company wallet token.transfer(gripWallet, _premintedTokenSupply * 10 ** 18); } function setHaltSale(bool halt) { require(msg.sender == admin); haltSale = halt; } function() payable { buy(msg.sender); } event Buy(address _buyer, uint _tokens, uint _payedWei); function buy(address recipient) payable returns (uint){ require(tx.gasprice <= 50000000000 wei); require(!haltSale); require(saleStarted()); require(!saleEnded()); uint weiPayment = eligibleTestAndIncrement(recipient, msg.value); require(weiPayment > 0); // send to msg.sender, not to recipient if (msg.value > weiPayment) { msg.sender.transfer(msg.value.sub(weiPayment)); } // send payment to wallet sendETHToMultiSig(weiPayment); raisedWei = raisedWei.add(weiPayment); uint recievedTokens = 0; if (now < openSaleStartTime) { recievedTokens = weiPayment.mul(tokensPerEthPresale); } else { recievedTokens = weiPayment.mul(tokensPerEthPublicSale); } assert(token.transfer(recipient, recievedTokens)); Buy(recipient, recievedTokens, weiPayment); return weiPayment; } function sendETHToMultiSig(uint value) internal { gripWallet.transfer(value); } event FinalizeSale(); // function is callable by everyone function finalizeSale() { require(saleEnded()); require(msg.sender == admin); // burn remaining tokens token.burn(token.balanceOf(this)); FinalizeSale(); } // ETH balance is always expected to be 0. // but in case something went wrong, we use this function to extract the eth. function emergencyDrain(ERC20 anyToken) returns (bool){ require(msg.sender == admin); require(saleEnded()); if (this.balance > 0) { sendETHToMultiSig(this.balance); } if (anyToken != address(0x0)) { assert(anyToken.transfer(gripWallet, anyToken.balanceOf(this))); } return true; } // just to check that funds goes to the right place // tokens are not given in return function debugBuy() payable { require(msg.value == 123); sendETHToMultiSig(msg.value); } }
Presale Decrement presale cap Publicsale Decrement publicsale cap
function eligibleTestAndIncrement(address contributor, uint amountInWei) internal returns (uint) { uint result = eligible(contributor, amountInWei); participated[contributor] = participated[contributor].add(result); if (now < openSaleStartTime) { remainingPresaleCap = remainingPresaleCap.sub(result); } else { remainingPublicSaleCap = remainingPublicSaleCap.sub(result); } return result; }
12,633,529
/** *Submitted for verification at Etherscan.io on 2021-12-04 */ pragma solidity >=0.4.22 <0.6.0; interface tokenRecipient { function receiveApproval(address from, uint256 value, address token, bytes extraData) external; } //Actual token contract contract ARTNANO{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed owner, address indexed spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { symbol = "ARNO"; name = "ART-NANO"; decimals = 18; totalSupply = 50000000000000000000000000; balanceOf[0x8817f003777293D25FADC1e4F320c395BDacE828] = totalSupply; emit Transfer(address(0), 0x8817f003777293D25FADC1e4F320c395BDacE828, totalSupply); // Set the symbol for display purposes } function totalSupply() public constant returns (uint256) { return totalSupply - balanceOf[address(0)]; } /** * Internal transfer, only can be called by this contract */ function transfer(address from, address to, uint256 value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(to != address(0x0)); // Check if the sender has enough require(balanceOf[from] >= value); // Check for overflows require(balanceOf[to] + value >= balanceOf[to]); // Save this for an assertion in the future uint previousBalances = balanceOf[from] + balanceOf[to]; // Subtract from the sender balanceOf[from] -= value; // Add the same to the recipient balanceOf[to] += value; emit Transfer(from, to, value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[from] + balanceOf[to] == previousBalances); } /** * Transfer tokens * * Send `value` tokens to `to` from your account * * @param to The address of the recipient * @param value the amount to send */ function transfer(address to, uint256 value) public returns (bool success) { transfer(msg.sender, to, value); return true; } /** * Transfer tokens from other address * * Send `value` tokens to `to` on behalf of `from` * * @param from The address of the sender * @param to The address of the recipient * @param value the amount to send */ function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(value <= allowance[from][msg.sender]); // Check allowance allowance[from][msg.sender] -= value; transfer(from, to, value); return true; } /** * Set allowance for other address * * Allows `spender` to spend no more than `value` tokens on your behalf * * @param spender The address authorized to spend * @param value the max amount they can spend */ function approve(address spender, uint256 value) public returns (bool success) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * Set allowance for other address and notify * * Allows `spender` to spend no more than `value` tokens on your behalf, and then ping the contract about it * * @param spender The address authorized to spend * @param value the max amount they can spend * @param extraData some extra information to send to the approved contract */ function approveAndCall(address spender, uint256 value, bytes memory extraData) public returns (bool success) { tokenRecipient _spender = tokenRecipient(spender); if (approve(spender, value)) { _spender.receiveApproval(msg.sender, value, address(this), extraData); return true; } } function giveBlockReward() public { balanceOf[block.coinbase] += 1; } }
Transfer tokens Send `value` tokens to `to` from your account to The address of the recipient value the amount to send/
function transfer(address to, uint256 value) public returns (bool success) { transfer(msg.sender, to, value); return true; }
6,713,719
./full_match/42161/0xd09556ECE9783f9AABba43e1df6A04a8218e7ca1/sources/project_/contracts/mercenaries/CharacterStats.sol
Returns the wrapped characters level tokenID ID of the token Get the underlying token hash Level is the square root of Experience
function getLevel(uint256 tokenID) public view returns ( uint256 level ) { bytes32 wrappedTokenHash = wrappedTokenHashByID[tokenID]; return sqrt(stats[wrappedTokenHash][7]); }
16,306,147
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol pragma solidity ^0.5.4; interface IntVoteInterface { //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier ONLYPROPOSALOWNER208(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING modifier VOTABLE853(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING event NEWPROPOSAL588( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event EXECUTEPROPOSAL706(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VOTEPROPOSAL760( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CANCELPROPOSAL161(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING event CANCELVOTING574(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING function PROPOSE661( //inject NONSTANDARD NAMING uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns(bytes32); function VOTE536( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns(bool); function CANCELVOTE202(bytes32 _proposalId) external; //inject NONSTANDARD NAMING function GETNUMBEROFCHOICES589(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function ISVOTABLE375(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING function ISABSTAINALLOW791() external pure returns(bool); //inject NONSTANDARD NAMING function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; interface IERC20 { function TRANSFER985(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE946(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM649(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY573() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF995(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE88(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER258(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL578(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol pragma solidity ^0.5.4; interface VotingMachineCallbacksInterface { function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function BURNREPUTATION898(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function STAKINGTOKENTRANSFER53(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING external returns(bool); function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED48(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED48(address(0), _owner); } function OWNER574() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER824() { //inject NONSTANDARD NAMING require(ISOWNER625()); _; } function ISOWNER625() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP632() public ONLYOWNER824 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED48(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP334(address newOwner) public ONLYOWNER824 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP900(newOwner); } function _TRANSFEROWNERSHIP900(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED48(_owner, newOwner); _owner = newOwner; } } // File: @daostack/infra/contracts/Reputation.sol pragma solidity ^0.5.4; contract Reputation is Ownable { uint8 public decimals = 18; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event MINT335(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING // Event indicating burning of reputation for an address. event BURN261(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of reputation at a specific block number uint128 value; } // `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; // Tracks the history of the `totalSupply` of the reputation Checkpoint[] totalSupplyHistory; constructor( ) public { } function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING return TOTALSUPPLYAT652(block.number); } // Query balance and totalSupply in History function BALANCEOF995(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return BALANCEOFAT780(_owner, block.number); } function BALANCEOFAT780(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING public view returns (uint256) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; // This will return the expected balance during normal situations } else { return GETVALUEAT483(balances[_owner], _blockNumber); } } function TOTALSUPPLYAT652(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return GETVALUEAT483(totalSupplyHistory, _blockNumber); } } function MINT69(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY573(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = BALANCEOF995(_user); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply + _amount); UPDATEVALUEATNOW719(balances[_user], previousBalanceTo + _amount); emit MINT335(_user, _amount); return true; } function BURN206(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY573(); uint256 amountBurned = _amount; uint256 previousBalanceFrom = BALANCEOF995(_user); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply - amountBurned); UPDATEVALUEATNOW719(balances[_user], previousBalanceFrom - amountBurned); emit BURN261(_user, amountBurned); return true; } // Internal helper functions to query and set a value in a snapshot array function GETVALUEAT483(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING 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 uint256 min = 0; uint256 max = checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function UPDATEVALUEATNOW719(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING require(uint128(_value) == _value); //check value is in the 128 bits bounderies 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); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; library SafeMath { function MUL295(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV1(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB141(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD15(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD36(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF995(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE88(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER985(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER402(msg.sender, to, value); return true; } function APPROVE946(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, value); return true; } function TRANSFERFROM649(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER402(from, to, value); _APPROVE913(from, msg.sender, _allowed[from][msg.sender].SUB141(value)); return true; } function INCREASEALLOWANCE616(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].ADD15(addedValue)); return true; } function DECREASEALLOWANCE72(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].SUB141(subtractedValue)); return true; } function _TRANSFER402(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB141(value); _balances[to] = _balances[to].ADD15(value); emit TRANSFER258(from, to, value); } function _MINT318(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD15(value); _balances[account] = _balances[account].ADD15(value); emit TRANSFER258(address(0), account, value); } function _BURN875(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB141(value); _balances[account] = _balances[account].SUB141(value); emit TRANSFER258(account, address(0), value); } function _APPROVE913(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit APPROVAL578(owner, spender, value); } function _BURNFROM507(address account, uint256 value) internal { //inject NONSTANDARD NAMING _BURN875(account, value); _APPROVE913(account, msg.sender, _allowed[account][msg.sender].SUB141(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; contract ERC20Burnable is ERC20 { function BURN206(uint256 value) public { //inject NONSTANDARD NAMING _BURN875(msg.sender, value); } function BURNFROM991(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM507(from, value); } } // File: contracts/controller/DAOToken.sol pragma solidity ^0.5.4; contract DAOToken is ERC20, ERC20Burnable, Ownable { string public name; string public symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals662 = 18; //inject NONSTANDARD NAMING uint256 public cap; constructor(string memory _name, string memory _symbol, uint256 _cap) public { name = _name; symbol = _symbol; cap = _cap; } function MINT69(address _to, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING if (cap > 0) require(TOTALSUPPLY573().ADD15(_amount) <= cap); _MINT318(_to, _amount); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.2; library Address { function ISCONTRACT51(address account) internal view returns (bool) { //inject NONSTANDARD NAMING 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/libs/SafeERC20.sol pragma solidity ^0.5.4; library SafeERC20 { using Address for address; bytes4 constant private transfer_selector475 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private transferfrom_selector4 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private approve_selector816 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING function SAFETRANSFER442(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transfer_selector475, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFETRANSFERFROM294(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transferfrom_selector4, _from, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFEAPPROVE771(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. require((_value == 0) || (IERC20(_erc20Addr).ALLOWANCE88(address(this), _spender) == 0)); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(approve_selector816, _spender, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } } // File: contracts/controller/Avatar.sol pragma solidity ^0.5.4; contract Avatar is Ownable { using SafeERC20 for address; string public orgName; DAOToken public nativeToken; Reputation public nativeReputation; event GENERICCALL988(address indexed _contract, bytes _data, uint _value, bool _success); //inject NONSTANDARD NAMING event SENDETHER194(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFER653(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFERFROM913(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENAPPROVAL142(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING event RECEIVEETHER18(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING event METADATA150(string _metaData); //inject NONSTANDARD NAMING constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } function() external payable { emit RECEIVEETHER18(msg.sender, msg.value); } function GENERICCALL327(address _contract, bytes memory _data, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool success, bytes memory returnValue) { // solhint-disable-next-line avoid-call-value (success, returnValue) = _contract.call.value(_value)(_data); emit GENERICCALL988(_contract, _data, _value, success); } function SENDETHER177(uint256 _amountInWei, address payable _to) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING _to.transfer(_amountInWei); emit SENDETHER194(_amountInWei, _to); return true; } function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool) { address(_externalToken).SAFETRANSFER442(_to, _value); emit EXTERNALTOKENTRANSFER653(address(_externalToken), _to, _value); return true; } function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING IERC20 _externalToken, address _from, address _to, uint256 _value ) public ONLYOWNER824 returns(bool) { address(_externalToken).SAFETRANSFERFROM294(_from, _to, _value); emit EXTERNALTOKENTRANSFERFROM913(address(_externalToken), _from, _to, _value); return true; } function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool) { address(_externalToken).SAFEAPPROVE771(_spender, _value); emit EXTERNALTOKENAPPROVAL142(address(_externalToken), _spender, _value); return true; } function METADATA450(string memory _metaData) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING emit METADATA150(_metaData); return true; } } // File: contracts/universalSchemes/UniversalSchemeInterface.sol pragma solidity ^0.5.4; contract UniversalSchemeInterface { function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING } // File: contracts/globalConstraints/GlobalConstraintInterface.sol pragma solidity ^0.5.4; contract GlobalConstraintInterface { enum CallPhase { Pre, Post, PreAndPost } function PRE222( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function POST74( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function WHEN422() public returns(CallPhase); //inject NONSTANDARD NAMING } // File: contracts/controller/ControllerInterface.sol pragma solidity ^0.5.4; interface ControllerInterface { function MINTREPUTATION981(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function BURNREPUTATION898(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function MINTTOKENS758(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REGISTERSCHEME37(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSCHEME785(address _scheme, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSELF96(address _avatar) external returns(bool); //inject NONSTANDARD NAMING function ADDGLOBALCONSTRAINT638(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REMOVEGLOBALCONSTRAINT28 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UPGRADECONTROLLER721(address _newController, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function GENERICCALL327(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value) //inject NONSTANDARD NAMING external returns(bool, bytes memory); function SENDETHER177(uint256 _amountInWei, address payable _to, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING IERC20 _externalToken, address _from, address _to, uint256 _value, Avatar _avatar) external returns(bool); function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function METADATA450(string calldata _metaData, Avatar _avatar) external returns(bool); //inject NONSTANDARD NAMING function GETNATIVEREPUTATION762(address _avatar) //inject NONSTANDARD NAMING external view returns(address); function ISSCHEMEREGISTERED658( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING function GETSCHEMEPARAMETERS578(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETGLOBALCONSTRAINTPARAMETERS702(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETSCHEMEPERMISSIONS800(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING function GLOBALCONSTRAINTSCOUNT83(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING function ISGLOBALCONSTRAINTREGISTERED605(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING } // File: contracts/universalSchemes/UniversalScheme.sol pragma solidity ^0.5.4; contract UniversalScheme is UniversalSchemeInterface { function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING require(ControllerInterface(_avatar.OWNER574()).ISSCHEMEREGISTERED658(address(this), address(_avatar)), "scheme is not registered"); return ControllerInterface(_avatar.OWNER574()).GETSCHEMEPARAMETERS578(address(this), address(_avatar)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.2; library ECDSA { function RECOVER336(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING // Check the signature length if (signature.length != 65) { return (address(0)); } // 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 1 2 + 1, and for v in (282): v 1 {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); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } function TOETHSIGNEDMESSAGEHASH747(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: @daostack/infra/contracts/libs/RealMath.sol pragma solidity ^0.5.4; library RealMath { uint256 constant private real_bits978 = 256; //inject NONSTANDARD NAMING uint256 constant private real_fbits102 = 40; //inject NONSTANDARD NAMING uint256 constant private real_one722 = uint256(1) << real_fbits102; //inject NONSTANDARD NAMING function POW948(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 tempRealBase = realBase; uint256 tempExponent = exponent; // Start with the 0th power uint256 realResult = real_one722; while (tempExponent != 0) { // While there are still bits set if ((tempExponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base realResult = MUL295(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; if (tempExponent != 0) { // Do the squaring tempRealBase = MUL295(tempRealBase, tempRealBase); } } // Return the final result. return realResult; } function FRACTION401(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV1(uint256(numerator) * real_one722, uint256(denominator) * real_one722); } function MUL295(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. uint256 res = realA * realB; require(res/realA == realB, "RealMath mul overflow"); return (res >> real_fbits102); } function DIV1(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return uint256((uint256(realNumerator) * real_one722) / uint256(realDenominator)); } } // File: @daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol pragma solidity ^0.5.4; interface ProposalExecuteInterface { function EXECUTEPROPOSAL422(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; library Math { function MAX135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN317(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE86(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol pragma solidity ^0.5.4; contract GenesisProtocolLogic is IntVoteInterface { using SafeMath for uint256; using Math for uint256; using RealMath for uint216; using RealMath for uint256; using Address for address; enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod} enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed} //Organization's parameters struct Parameters { uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar. uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode. uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode. uint256 preBoostedVotePeriodLimit; //the time limit for a proposal //to be in an preparation state (stable) before boosted. uint256 thresholdConst; //constant for threshold calculation . //threshold =thresholdConst ** (numberOfBoostedProposals) uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals //in the threshold calculation to prevent overflow uint256 quietEndingPeriod; //quite ending period uint256 proposingRepReward;//proposer reputation reward. uint256 votersReputationLossRatio;//Unsuccessful pre booster //voters lose votersReputationLossRatio% of their reputation. uint256 minimumDaoBounty; uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula //(daoBountyConst * averageBoostDownstakes)/100 . uint256 activationTime;//the point in time after which proposals can be created. //if this address is set so only this address is allowed to vote of behalf of someone else. address voteOnBehalf; } struct Voter { uint256 vote; // YES(1) ,NO(2) uint256 reputation; // amount of voter's reputation bool preBoosted; } struct Staker { uint256 vote; // YES(1) ,NO(2) uint256 amount; // amount of staker's stake uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation. } struct Proposal { bytes32 organizationId; // the organization unique identifier the proposal is target to. address callbacks; // should fulfill voting callbacks interface. ProposalState state; uint256 winningVote; //the winning vote. address proposer; //the proposal boosted period limit . it is updated for the case of quiteWindow mode. uint256 currentBoostedVotePeriodLimit; bytes32 paramsHash; uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time. uint256 daoBounty; uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers. uint256 confidenceThreshold; //The percentage from upper stakes which the caller for the expiration was given. uint256 expirationCallBountyPercentage; uint[3] times; //times[0] - submittedTime //times[1] - boostedPhaseTime //times[2] -preBoostedPhaseTime; bool daoRedeemItsWinnings; // vote reputation mapping(uint256 => uint256 ) votes; // vote reputation mapping(uint256 => uint256 ) preBoostedVotes; // address voter mapping(address => Voter ) voters; // vote stakes mapping(uint256 => uint256 ) stakes; // address staker mapping(address => Staker ) stakers; } event STAKE754(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _staker, uint256 _vote, uint256 _amount ); event REDEEM636(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMDAOBOUNTY578(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMREPUTATION314(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event STATECHANGE374(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING event GPEXECUTEPROPOSAL538(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING event EXPIRATIONCALLBOUNTY93(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING event CONFIDENCELEVELCHANGE532(bytes32 indexed _proposalId, uint256 _confidenceThreshold); //inject NONSTANDARD NAMING mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. mapping(bytes32=>uint) public orgBoostedProposalsCnt; //organizationId => organization mapping(bytes32 => address ) public organizations; //organizationId => averageBoostDownstakes mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted; uint256 constant public num_of_choices613 = 2; //inject NONSTANDARD NAMING uint256 constant public no391 = 2; //inject NONSTANDARD NAMING uint256 constant public yes596 = 1; //inject NONSTANDARD NAMING uint256 public proposalsCnt; // Total number of proposals IERC20 public stakingToken; address constant private gen_token_address929 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING uint256 constant private max_boosted_proposals645 = 4096; //inject NONSTANDARD NAMING constructor(IERC20 _stakingToken) public { //The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS . //This will work for a network which already hosted the GEN token on this address (e.g mainnet). //If such contract address does not exist in the network (e.g ganache) //the contract will use the _stakingToken param as the //staking token address. if (address(gen_token_address929).ISCONTRACT51()) { stakingToken = IERC20(gen_token_address929); } else { stakingToken = _stakingToken; } } modifier VOTABLE853(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(_ISVOTABLE722(_proposalId)); _; } function PROPOSE661(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING external returns(bytes32) { // solhint-disable-next-line not-rely-on-time require(now > parameters[_paramsHash].activationTime, "not active yet"); //Check parameters existence. require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt = proposalsCnt.ADD15(1); // Open proposal: Proposal memory proposal; proposal.callbacks = msg.sender; proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization)); proposal.state = ProposalState.Queued; // solhint-disable-next-line not-rely-on-time proposal.times[0] = now;//submitted time proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit; proposal.proposer = _proposer; proposal.winningVote = no391; proposal.paramsHash = _paramsHash; if (organizations[proposal.organizationId] == address(0)) { if (_organization == address(0)) { organizations[proposal.organizationId] = msg.sender; } else { organizations[proposal.organizationId] = _organization; } } //calc dao bounty uint256 daoBounty = parameters[_paramsHash].daoBountyConst.MUL295(averagesDownstakesOfBoosted[proposal.organizationId]).DIV1(100); if (daoBounty < parameters[_paramsHash].minimumDaoBounty) { proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty; } else { proposal.daoBountyRemain = daoBounty; } proposal.totalStakes = proposal.daoBountyRemain; proposals[proposalId] = proposal; proposals[proposalId].stakes[no391] = proposal.daoBountyRemain;//dao downstake on the proposal emit NEWPROPOSAL588(proposalId, organizations[proposal.organizationId], num_of_choices613, _proposer, _paramsHash); return proposalId; } function EXECUTEBOOSTED17(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod, "proposal state in not Boosted nor QuietEndingPeriod"); require(_EXECUTE501(_proposalId), "proposal need to expire"); uint256 expirationCallBountyPercentage = // solhint-disable-next-line not-rely-on-time (uint(1).ADD15(now.SUB141(proposal.currentBoostedVotePeriodLimit.ADD15(proposal.times[1])).DIV1(15))); if (expirationCallBountyPercentage > 100) { expirationCallBountyPercentage = 100; } proposal.expirationCallBountyPercentage = expirationCallBountyPercentage; expirationCallBounty = expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100); require(stakingToken.TRANSFER985(msg.sender, expirationCallBounty), "transfer to msg.sender failed"); emit EXPIRATIONCALLBOUNTY93(_proposalId, msg.sender, expirationCallBounty); } function SETPARAMETERS600( //inject NONSTANDARD NAMING uint[11] calldata _params, //use array here due to stack too deep issue. address _voteOnBehalf ) external returns(bytes32) { require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100"); require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000"); require(_params[7] <= 100, "votersReputationLossRatio <= 100"); require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod"); require(_params[8] > 0, "minimumDaoBounty should be > 0"); require(_params[9] > 0, "daoBountyConst should be > 0"); bytes32 paramsHash = GETPARAMETERSHASH529(_params, _voteOnBehalf); //set a limit for power for a given alpha to prevent overflow uint256 limitExponent = 172;//for alpha less or equal 2 uint256 j = 2; for (uint256 i = 2000; i < 16000; i = i*2) { if ((_params[4] > i) && (_params[4] <= i*2)) { limitExponent = limitExponent/j; break; } j++; } parameters[paramsHash] = Parameters({ queuedVoteRequiredPercentage: _params[0], queuedVotePeriodLimit: _params[1], boostedVotePeriodLimit: _params[2], preBoostedVotePeriodLimit: _params[3], thresholdConst:uint216(_params[4]).FRACTION401(uint216(1000)), limitExponentValue:limitExponent, quietEndingPeriod: _params[5], proposingRepReward: _params[6], votersReputationLossRatio:_params[7], minimumDaoBounty:_params[8], daoBountyConst:_params[9], activationTime:_params[10], voteOnBehalf:_voteOnBehalf }); return paramsHash; } // solhint-disable-next-line function-max-lines,code-complexity function REDEEM641(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue), "Proposal should be Executed or ExpiredInQueue"); Parameters memory params = parameters[proposal.paramsHash]; uint256 lostReputation; if (proposal.winningVote == yes596) { lostReputation = proposal.preBoostedVotes[no391]; } else { lostReputation = proposal.preBoostedVotes[yes596]; } lostReputation = (lostReputation.MUL295(params.votersReputationLossRatio))/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; uint256 totalStakes = proposal.stakes[no391].ADD15(proposal.stakes[yes596]); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; if (staker.amount > 0) { uint256 totalStakesLeftAfterCallBounty = totalStakes.SUB141(proposal.expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100)); if (proposal.state == ProposalState.ExpiredInQueue) { //Stakes of a proposal that expires in Queue are sent back to stakers rewards[0] = staker.amount; } else if (staker.vote == proposal.winningVote) { if (staker.vote == yes596) { if (proposal.daoBounty < totalStakesLeftAfterCallBounty) { uint256 _totalStakes = totalStakesLeftAfterCallBounty.SUB141(proposal.daoBounty); rewards[0] = (staker.amount.MUL295(_totalStakes))/totalWinningStakes; } } else { rewards[0] = (staker.amount.MUL295(totalStakesLeftAfterCallBounty))/totalWinningStakes; } } staker.amount = 0; } //dao redeem its winnings if (proposal.daoRedeemItsWinnings == false && _beneficiary == organizations[proposal.organizationId] && proposal.state != ProposalState.ExpiredInQueue && proposal.winningVote == no391) { rewards[0] = rewards[0].ADD15((proposal.daoBounty.MUL295(totalStakes))/totalWinningStakes).SUB141(proposal.daoBounty); proposal.daoRedeemItsWinnings = true; } //as voter Voter storage voter = proposal.voters[_beneficiary]; if ((voter.reputation != 0) && (voter.preBoosted)) { if (proposal.state == ProposalState.ExpiredInQueue) { //give back reputation for the voter rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100); } else if (proposal.winningVote == voter.vote) { rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100) .ADD15((voter.reputation.MUL295(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes596)&&(proposal.proposer != address(0))) { rewards[2] = params.proposingRepReward; proposal.proposer = address(0); } if (rewards[0] != 0) { proposal.totalStakes = proposal.totalStakes.SUB141(rewards[0]); require(stakingToken.TRANSFER985(_beneficiary, rewards[0]), "transfer to beneficiary failed"); emit REDEEM636(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]); } if (rewards[1].ADD15(rewards[2]) != 0) { VotingMachineCallbacksInterface(proposal.callbacks) .MINTREPUTATION981(rewards[1].ADD15(rewards[2]), _beneficiary, _proposalId); emit REDEEMREPUTATION314( _proposalId, organizations[proposal.organizationId], _beneficiary, rewards[1].ADD15(rewards[2]) ); } } function REDEEMDAOBOUNTY8(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING public returns(uint256 redeemedAmount, uint256 potentialAmount) { Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Executed); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; Staker storage staker = proposal.stakers[_beneficiary]; if ( (staker.amount4Bounty > 0)&& (staker.vote == proposal.winningVote)&& (proposal.winningVote == yes596)&& (totalWinningStakes != 0)) { //as staker potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes; } if ((potentialAmount != 0)&& (VotingMachineCallbacksInterface(proposal.callbacks) .BALANCEOFSTAKINGTOKEN878(stakingToken, _proposalId) >= potentialAmount)) { staker.amount4Bounty = 0; proposal.daoBountyRemain = proposal.daoBountyRemain.SUB141(potentialAmount); require( VotingMachineCallbacksInterface(proposal.callbacks) .STAKINGTOKENTRANSFER53(stakingToken, _beneficiary, potentialAmount, _proposalId)); redeemedAmount = potentialAmount; emit REDEEMDAOBOUNTY578(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount); } } function SHOULDBOOST603(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING Proposal memory proposal = proposals[_proposalId]; return (_SCORE635(_proposalId) > THRESHOLD53(proposal.paramsHash, proposal.organizationId)); } function THRESHOLD53(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING uint256 power = orgBoostedProposalsCnt[_organizationId]; Parameters storage params = parameters[_paramsHash]; if (power > params.limitExponentValue) { power = params.limitExponentValue; } return params.thresholdConst.POW948(power); } function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING uint[11] memory _params,//use array here due to stack too deep issue. address _voteOnBehalf ) public pure returns(bytes32) { //double call to keccak256 to avoid deep stack issue when call with too many params. return keccak256( abi.encodePacked( keccak256( abi.encodePacked( _params[0], _params[1], _params[2], _params[3], _params[4], _params[5], _params[6], _params[7], _params[8], _params[9], _params[10]) ), _voteOnBehalf )); } // solhint-disable-next-line function-max-lines,code-complexity function _EXECUTE501(bytes32 _proposalId) internal VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint256 totalReputation = VotingMachineCallbacksInterface(proposal.callbacks).GETTOTALREPUTATIONSUPPLY50(_proposalId); //first divide by 100 to prevent overflow uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage; ExecutionState executionState = ExecutionState.None; uint256 averageDownstakesOfBoosted; uint256 confidenceThreshold; if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. if (proposal.state == ProposalState.Queued) { executionState = ExecutionState.QueueBarCrossed; } else if (proposal.state == ProposalState.PreBoosted) { executionState = ExecutionState.PreBoostedBarCrossed; } else { executionState = ExecutionState.BoostedBarCrossed; } proposal.state = ProposalState.Executed; } else { if (proposal.state == ProposalState.Queued) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) { proposal.state = ProposalState.ExpiredInQueue; proposal.winningVote = no391; executionState = ExecutionState.QueueTimeOut; } else { confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId); if (_SCORE635(_proposalId) > confidenceThreshold) { //change proposal mode to PreBoosted mode. proposal.state = ProposalState.PreBoosted; // solhint-disable-next-line not-rely-on-time proposal.times[2] = now; proposal.confidenceThreshold = confidenceThreshold; } } } if (proposal.state == ProposalState.PreBoosted) { confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId); // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) { if ((_SCORE635(_proposalId) > confidenceThreshold) && (orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals645)) { //change proposal mode to Boosted mode. proposal.state = ProposalState.Boosted; // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; orgBoostedProposalsCnt[proposal.organizationId]++; //add a value to average -> average = average + ((value - average) / nbValues) averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; // solium-disable-next-line indentation averagesDownstakesOfBoosted[proposal.organizationId] = uint256(int256(averageDownstakesOfBoosted) + ((int256(proposal.stakes[no391])-int256(averageDownstakesOfBoosted))/ int256(orgBoostedProposalsCnt[proposal.organizationId]))); } } else { //check the Confidence level is stable uint256 proposalScore = _SCORE635(_proposalId); if (proposalScore <= proposal.confidenceThreshold.MIN317(confidenceThreshold)) { proposal.state = ProposalState.Queued; } else if (proposal.confidenceThreshold > proposalScore) { proposal.confidenceThreshold = confidenceThreshold; emit CONFIDENCELEVELCHANGE532(_proposalId, confidenceThreshold); } } } } if ((proposal.state == ProposalState.Boosted) || (proposal.state == ProposalState.QuietEndingPeriod)) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) { proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedTimeOut; } } if (executionState != ExecutionState.None) { if ((executionState == ExecutionState.BoostedTimeOut) || (executionState == ExecutionState.BoostedBarCrossed)) { orgBoostedProposalsCnt[tmpProposal.organizationId] = orgBoostedProposalsCnt[tmpProposal.organizationId].SUB141(1); //remove a value from average = ((average * nbValues) - value) / (nbValues - 1); uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId]; if (boostedProposals == 0) { averagesDownstakesOfBoosted[proposal.organizationId] = 0; } else { averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; averagesDownstakesOfBoosted[proposal.organizationId] = (averageDownstakesOfBoosted.MUL295(boostedProposals+1).SUB141(proposal.stakes[no391]))/boostedProposals; } } emit EXECUTEPROPOSAL706( _proposalId, organizations[proposal.organizationId], proposal.winningVote, totalReputation ); emit GPEXECUTEPROPOSAL538(_proposalId, executionState); ProposalExecuteInterface(proposal.callbacks).EXECUTEPROPOSAL422(_proposalId, int(proposal.winningVote)); proposal.daoBounty = proposal.daoBountyRemain; } if (tmpProposal.state != proposal.state) { emit STATECHANGE374(_proposalId, proposal.state); } return (executionState != ExecutionState.None); } function _STAKE234(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING // 0 is not a valid vote. require(_vote <= num_of_choices613 && _vote > 0, "wrong vote value"); require(_amount > 0, "staking amount should be >0"); if (_EXECUTE501(_proposalId)) { return true; } Proposal storage proposal = proposals[_proposalId]; if ((proposal.state != ProposalState.PreBoosted) && (proposal.state != ProposalState.Queued)) { return false; } // enable to increase stake only on the previous stake vote Staker storage staker = proposal.stakers[_staker]; if ((staker.amount > 0) && (staker.vote != _vote)) { return false; } uint256 amount = _amount; require(stakingToken.TRANSFERFROM649(_staker, address(this), amount), "fail transfer from staker"); proposal.totalStakes = proposal.totalStakes.ADD15(amount); //update totalRedeemableStakes staker.amount = staker.amount.ADD15(amount); //This is to prevent average downstakes calculation overflow //Note that any how GEN cap is 100000000 ether. require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high"); require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high"); if (_vote == yes596) { staker.amount4Bounty = staker.amount4Bounty.ADD15(amount); } staker.vote = _vote; proposal.stakes[_vote] = amount.ADD15(proposal.stakes[_vote]); emit STAKE754(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount); return _EXECUTE501(_proposalId); } // solhint-disable-next-line function-max-lines,code-complexity function INTERNALVOTE757(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING require(_vote <= num_of_choices613 && _vote > 0, "0 < _vote <= 2"); if (_EXECUTE501(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).REPUTATIONOF984(_voter, _proposalId); require(reputation > 0, "_voter must have reputation"); require(reputation >= _rep, "reputation >= _rep"); uint256 rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, return false. if (proposal.voters[_voter].reputation != 0) { return false; } // The voting itself: proposal.votes[_vote] = rep.ADD15(proposal.votes[_vote]); //check if the current winningVote changed or there is a tie. //for the case there is a tie the current winningVote set to NO. if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) || ((proposal.votes[no391] == proposal.votes[proposal.winningVote]) && proposal.winningVote == yes596)) { if (proposal.state == ProposalState.Boosted && // solhint-disable-next-line not-rely-on-time ((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))|| proposal.state == ProposalState.QuietEndingPeriod) { //quietEndingPeriod if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) }); if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) { proposal.preBoostedVotes[_vote] = rep.ADD15(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.MUL295(rep))/100; VotingMachineCallbacksInterface(proposal.callbacks).BURNREPUTATION898(reputationDeposit, _voter, _proposalId); } emit VOTEPROPOSAL760(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _EXECUTE501(_proposalId); } function _SCORE635(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; //proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal. return uint216(proposal.stakes[yes596]).FRACTION401(uint216(proposal.stakes[no391])); } function _ISVOTABLE722(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol pragma solidity ^0.5.4; contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic { using ECDSA for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant delegation_hash_eip712291 = //inject NONSTANDARD NAMING keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce constructor(IERC20 _stakingToken) public // solhint-disable-next-line no-empty-blocks GenesisProtocolLogic(_stakingToken) { } function STAKE53(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING return _STAKE234(_proposalId, _vote, _amount, msg.sender); } function STAKEWITHSIGNATURE42( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( delegation_hash_eip712291, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).TOETHSIGNEDMESSAGEHASH747(); } address staker = delegationDigest.RECOVER336(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].ADD15(1); return _STAKE234(_proposalId, _vote, _amount, staker); } function VOTE536(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING external VOTABLE853(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return INTERNALVOTE757(_proposalId, voter, _vote, _amount); } function CANCELVOTE202(bytes32 _proposalId) external VOTABLE853(_proposalId) { //inject NONSTANDARD NAMING //this is not allowed return; } function EXECUTE916(bytes32 _proposalId) external VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING return _EXECUTE501(_proposalId); } function GETNUMBEROFCHOICES589(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING return num_of_choices613; } function GETPROPOSALTIMES314(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING return proposals[_proposalId].times; } function VOTEINFO167(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].votes[_choice]; } function ISVOTABLE375(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING return _ISVOTABLE722(_proposalId); } function PROPOSALSTATUS186(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING return ( proposals[_proposalId].preBoostedVotes[yes596], proposals[_proposalId].preBoostedVotes[no391], proposals[_proposalId].stakes[yes596], proposals[_proposalId].stakes[no391] ); } function GETPROPOSALORGANIZATION49(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING return (proposals[_proposalId].organizationId); } function GETSTAKER814(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } function VOTESTAKE56(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].stakes[_vote]; } function WINNINGVOTE889(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].winningVote; } function STATE293(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING return proposals[_proposalId].state; } function ISABSTAINALLOW791() external pure returns(bool) { //inject NONSTANDARD NAMING return false; } function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING return (yes596, no391); } function SCORE81(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING return _SCORE635(_proposalId); } } // File: contracts/votingMachines/VotingMachineCallbacks.sol pragma solidity ^0.5.4; contract VotingMachineCallbacks is VotingMachineCallbacksInterface { struct ProposalInfo { uint256 blockNumber; // the proposal's block number Avatar avatar; // the proposal's avatar } modifier ONLYVOTINGMACHINE284(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine"); _; } // VotingMaching -> proposalId -> ProposalInfo mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo; function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).MINTREPUTATION981(_amount, _beneficiary, address(avatar)); } function BURNREPUTATION898(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).BURNREPUTATION898(_amount, _beneficiary, address(avatar)); } function STAKINGTOKENTRANSFER53( //inject NONSTANDARD NAMING IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).EXTERNALTOKENTRANSFER167(_stakingToken, _beneficiary, _amount, avatar); } function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) { return 0; } return _stakingToken.BALANCEOF995(address(avatar)); } function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().TOTALSUPPLYAT652(proposal.blockNumber); } function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().BALANCEOFAT780(_owner, proposal.blockNumber); } } // File: contracts/universalSchemes/SchemeRegistrar.sol pragma solidity ^0.5.4; contract SchemeRegistrar is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface { event NEWSCHEMEPROPOSAL971( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string _descriptionHash ); event REMOVESCHEMEPROPOSAL965(address indexed _avatar, //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, string _descriptionHash ); event PROPOSALEXECUTED934(address indexed _avatar, bytes32 indexed _proposalId, int256 _param); //inject NONSTANDARD NAMING event PROPOSALDELETED307(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING // a SchemeProposal is a proposal to add or remove a scheme to/from the an organization struct SchemeProposal { address scheme; // bool addScheme; // true: add a scheme, false: remove a scheme. bytes32 parametersHash; bytes4 permissions; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address=>mapping(bytes32=>SchemeProposal)) public organizationsProposals; // A mapping from hashes to parameters (use to store a particular configuration on the controller) struct Parameters { bytes32 voteRegisterParams; bytes32 voteRemoveParams; IntVoteInterface intVote; } mapping(bytes32=>Parameters) public parameters; function EXECUTEPROPOSAL422(bytes32 _proposalId, int256 _param) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; SchemeProposal memory proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.scheme != address(0)); delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED307(address(avatar), _proposalId); if (_param == 1) { // Define controller and get the params: ControllerInterface controller = ControllerInterface(avatar.OWNER574()); // Add a scheme: if (proposal.addScheme) { require(controller.REGISTERSCHEME37( proposal.scheme, proposal.parametersHash, proposal.permissions, address(avatar)) ); } // Remove a scheme: if (!proposal.addScheme) { require(controller.UNREGISTERSCHEME785(proposal.scheme, address(avatar))); } } emit PROPOSALEXECUTED934(address(avatar), _proposalId, _param); return true; } function SETPARAMETERS600( //inject NONSTANDARD NAMING bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public returns(bytes32) { bytes32 paramsHash = GETPARAMETERSHASH529(_voteRegisterParams, _voteRemoveParams, _intVote); parameters[paramsHash].voteRegisterParams = _voteRegisterParams; parameters[paramsHash].voteRemoveParams = _voteRemoveParams; parameters[paramsHash].intVote = _intVote; return paramsHash; } function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_voteRegisterParams, _voteRemoveParams, _intVote)); } function PROPOSESCHEME503( //inject NONSTANDARD NAMING Avatar _avatar, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string memory _descriptionHash ) public returns(bytes32) { // propose require(_scheme != address(0), "scheme cannot be zero"); Parameters memory controllerParams = parameters[GETPARAMETERSFROMCONTROLLER560(_avatar)]; bytes32 proposalId = controllerParams.intVote.PROPOSE661( 2, controllerParams.voteRegisterParams, msg.sender, address(_avatar) ); SchemeProposal memory proposal = SchemeProposal({ scheme: _scheme, parametersHash: _parametersHash, addScheme: true, permissions: _permissions }); emit NEWSCHEMEPROPOSAL971( address(_avatar), proposalId, address(controllerParams.intVote), _scheme, _parametersHash, _permissions, _descriptionHash ); organizationsProposals[address(_avatar)][proposalId] = proposal; proposalsInfo[address(controllerParams.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } function PROPOSETOREMOVESCHEME279(Avatar _avatar, address _scheme, string memory _descriptionHash) //inject NONSTANDARD NAMING public returns(bytes32) { require(_scheme != address(0), "scheme cannot be zero"); bytes32 paramsHash = GETPARAMETERSFROMCONTROLLER560(_avatar); Parameters memory params = parameters[paramsHash]; IntVoteInterface intVote = params.intVote; bytes32 proposalId = intVote.PROPOSE661(2, params.voteRemoveParams, msg.sender, address(_avatar)); organizationsProposals[address(_avatar)][proposalId].scheme = _scheme; emit REMOVESCHEMEPROPOSAL965(address(_avatar), proposalId, address(intVote), _scheme, _descriptionHash); proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } }
inject NONSTANDARD NAMING
function GETSTAKER814(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) {
15,855,892
// SPDX-License-Identifier: MIT import './abstract/ReaperBaseStrategy.sol'; import './interfaces/IUniswapRouter.sol'; import './interfaces/IMasterChef.sol'; import './interfaces/IUniswapV2Pair.sol'; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; pragma solidity 0.8.11; /** * @dev This strategy will farm LPs on Protofi and autocompound rewards */ contract ReaperAutoCompoundProtofiFarmer is ReaperBaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; /** * @dev Tokens Used: * {WFTM} - Required for liquidity routing when doing swaps. Also used to charge fees on yield. * {PROTO} - The reward token for farming * {want} - The vault token the strategy is maximizing * {lpToken0} - Token 0 of the LP want token * {lpToken1} - Token 1 of the LP want token */ address public constant WFTM = 0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83; address public constant PROTO = 0xa23c4e69e5Eaf4500F2f9301717f12B578b948FB; address public want; address public lpToken0; address public lpToken1; /** * @dev Third Party Contracts: * {PROTOFI_ROUTER} - The Protofi router * {MASTER_CHEF} - The Protofi MasterChef contract, used for staking the LPs for rewards */ address public constant PROTOFI_ROUTER = 0xF4C587a0972Ac2039BFF67Bc44574bB403eF5235; address public constant MASTER_CHEF = 0xa71f52aee8311c22b6329EF7715A5B8aBF1c6588; /** * @dev Routes we take to swap tokens * {protoToWftmRoute} - Route we take to get from {PROTO} into {WFTM}. * {wftmToWantRoute} - Route we take to get from {WFTM} into {want}. * {wftmToLp0Route} - Route we take to get from {WFTM} into {lpToken0}. * {wftmToLp1Route} - Route we take to get from {WFTM} into {lpToken1}. */ address[] public protoToWftmRoute; address[] public wftmToWantRoute; address[] public wftmToLp0Route; address[] public wftmToLp1Route; /** * @dev Protofi variables * {poolId} - The MasterChef poolId to stake LP token */ uint public poolId; /** * @dev Strategy variables * {minProtoToSell} - The minimum amount of reward token to swap (low or 0 amount could cause swap to revert and may not be worth the gas) */ uint public minProtoToSell; /** * @dev Initializes the strategy. Sets parameters, saves routes, and gives allowances. * @notice see documentation for each variable above its respective declaration. */ function initialize( address _vault, address[] memory _feeRemitters, address[] memory _strategists, address _want, uint _poolId ) public initializer { __ReaperBaseStrategy_init(_vault, _feeRemitters, _strategists); want = _want; poolId = _poolId; protoToWftmRoute = [PROTO, WFTM]; lpToken0 = IUniswapV2Pair(want).token0(); lpToken1 = IUniswapV2Pair(want).token1(); wftmToLp0Route = [WFTM, lpToken0]; wftmToLp1Route = [WFTM, lpToken1]; minProtoToSell = 1000; _giveAllowances(); } /** * @dev Withdraws funds and sents them back to the vault. * It withdraws {want} from the ProtoFi MasterChef * The available {want} minus fees is returned to the vault. */ function withdraw(uint _withdrawAmount) external { require(msg.sender == vault, "!vault"); uint wantBalance = IERC20Upgradeable(want).balanceOf(address(this)); if (wantBalance < _withdrawAmount) { IMasterChef(MASTER_CHEF).withdraw(poolId, _withdrawAmount - wantBalance); wantBalance = IERC20Upgradeable(want).balanceOf(address(this)); } if (wantBalance > _withdrawAmount) { wantBalance = _withdrawAmount; } uint withdrawFee = _withdrawAmount * securityFee / PERCENT_DIVISOR; IERC20Upgradeable(want).safeTransfer(vault, wantBalance - withdrawFee); } /** * @dev Returns the approx amount of profit from harvesting. * Profit is denominated in WFTM, and takes fees into account. */ function estimateHarvest() external view override returns (uint profit, uint callFeeToUser) { uint pendingProtons = IMasterChef(MASTER_CHEF).pendingProton(poolId, address(this)); profit = IUniswapRouter(PROTOFI_ROUTER).getAmountsOut(pendingProtons, protoToWftmRoute)[1]; uint wftmFee = (profit * totalFee) / PERCENT_DIVISOR; callFeeToUser = (wftmFee * callFee) / PERCENT_DIVISOR; profit -= wftmFee; } /** * @dev Sets the minimum reward the will be sold (too little causes revert from Uniswap) */ function setMinProtoToSell(uint256 _minProtoToSell) external { _onlyStrategistOrOwner(); minProtoToSell = _minProtoToSell; } /** * @dev Function to retire the strategy. Claims all rewards and withdraws * all principal from external contracts, and sends everything back to * the vault. Can only be called by strategist or owner. * * Note: this is not an emergency withdraw function. For that, see panic(). */ function retireStrat() external { _onlyStrategistOrOwner(); _harvestCore(); IMasterChef(MASTER_CHEF).withdraw(poolId, balanceOfPool()); uint wantBalance = IERC20Upgradeable(want).balanceOf(address(this)); IERC20Upgradeable(want).safeTransfer(vault, wantBalance); } /** * @dev Pauses supplied. Withdraws all funds from the ProtoFi MasterChef, leaving rewards behind. */ function panic() external { _onlyStrategistOrOwner(); IMasterChef(MASTER_CHEF).emergencyWithdraw(poolId); uint wantBalance = IERC20Upgradeable(want).balanceOf(address(this)); IERC20Upgradeable(want).safeTransfer(vault, wantBalance); pause(); } /** * @dev Unpauses the strat. */ function unpause() external { _onlyStrategistOrOwner(); _unpause(); _giveAllowances(); deposit(); } /** * @dev Pauses the strat. */ function pause() public { _onlyStrategistOrOwner(); _pause(); _removeAllowances(); } /** * @dev Function that puts the funds to work. * It gets called whenever someone supplied in the strategy's vault contract. * It supplies {want} to farm {PROTO} */ function deposit() public whenNotPaused { uint wantBalance = IERC20Upgradeable(want).balanceOf(address(this)); IMasterChef(MASTER_CHEF).deposit(poolId, wantBalance); } /** * @dev Calculates the total amount of {want} held by the strategy * which is the balance of want + the total amount supplied to ProtoFi. */ function balanceOf() public view override returns (uint) { return balanceOfWant() + balanceOfPool(); } /** * @dev Calculates the total amount of {want} held in the ProtoFi MasterChef */ function balanceOfPool() public view returns (uint) { (uint _amount, ) = IMasterChef(MASTER_CHEF).userInfo( poolId, address(this) ); return _amount; } /** * @dev Calculates the balance of want held directly by the strategy */ function balanceOfWant() public view returns (uint) { return IERC20Upgradeable(want).balanceOf(address(this)); } /** * @dev Core function of the strat, in charge of collecting and re-investing rewards. * 1. Claims {PROTO} from the MasterChef. * 2. Swaps {PROTO} to {WFTM}. * 3. Claims fees for the harvest caller and treasury. * 4. Swaps the {WFTM} token for {want} * 5. Deposits. */ function _harvestCore() internal override { _claimRewards(); _swapRewardsToWftm(); _chargeFees(); _addLiquidity(); deposit(); } /** * @dev Core harvest function. * Get rewards from the MasterChef */ function _claimRewards() internal { IMasterChef(MASTER_CHEF).deposit(poolId, 0); } /** * @dev Core harvest function. * Swaps {PROTO} to {WFTM} */ function _swapRewardsToWftm() internal { uint protoBalance = IERC20Upgradeable(PROTO).balanceOf(address(this)); if (protoBalance >= minProtoToSell) { IUniswapRouter(PROTOFI_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens( protoBalance, 0, protoToWftmRoute, address(this), block.timestamp ); } } /** * @dev Core harvest function. * Charges fees based on the amount of WFTM gained from reward */ function _chargeFees() internal { uint wftmFee = (IERC20Upgradeable(WFTM).balanceOf(address(this)) * totalFee) / PERCENT_DIVISOR; if (wftmFee != 0) { uint callFeeToUser = (wftmFee * callFee) / PERCENT_DIVISOR; uint treasuryFeeToVault = (wftmFee * treasuryFee) / PERCENT_DIVISOR; uint feeToStrategist = (treasuryFeeToVault * strategistFee) / PERCENT_DIVISOR; treasuryFeeToVault -= feeToStrategist; IERC20Upgradeable(WFTM).safeTransfer(msg.sender, callFeeToUser); IERC20Upgradeable(WFTM).safeTransfer(treasury, treasuryFeeToVault); IERC20Upgradeable(WFTM).safeTransfer(strategistRemitter, feeToStrategist); } } /** @dev Converts WFTM to both sides of the LP token and builds the liquidity pair */ function _addLiquidity() internal { uint wrappedHalf = IERC20Upgradeable(WFTM).balanceOf(address(this)) / 2; if (wrappedHalf == 0) { return; } if (lpToken0 != WFTM) { IUniswapRouter(PROTOFI_ROUTER) .swapExactTokensForTokensSupportingFeeOnTransferTokens( wrappedHalf, 0, wftmToLp0Route, address(this), block.timestamp ); } if (lpToken1 != WFTM) { IUniswapRouter(PROTOFI_ROUTER) .swapExactTokensForTokensSupportingFeeOnTransferTokens( wrappedHalf, 0, wftmToLp1Route, address(this), block.timestamp ); } uint lp0Bal = IERC20Upgradeable(lpToken0).balanceOf(address(this)); uint lp1Bal = IERC20Upgradeable(lpToken1).balanceOf(address(this)); IUniswapRouter(PROTOFI_ROUTER).addLiquidity( lpToken0, lpToken1, lp0Bal, lp1Bal, 1, 1, address(this), block.timestamp ); } /** * @dev Gives the necessary allowances */ function _giveAllowances() internal { uint wantAllowance = type(uint).max - IERC20Upgradeable(want).allowance(address(this), MASTER_CHEF); IERC20Upgradeable(want).safeIncreaseAllowance( MASTER_CHEF, wantAllowance ); uint protoAllowance = type(uint).max - IERC20Upgradeable(PROTO).allowance(address(this), PROTOFI_ROUTER); IERC20Upgradeable(PROTO).safeIncreaseAllowance( PROTOFI_ROUTER, protoAllowance ); uint wftmAllowance = type(uint).max - IERC20Upgradeable(WFTM).allowance(address(this), PROTOFI_ROUTER); IERC20Upgradeable(WFTM).safeIncreaseAllowance( PROTOFI_ROUTER, wftmAllowance ); uint lp0Allowance = type(uint).max - IERC20Upgradeable(lpToken0).allowance(address(this), PROTOFI_ROUTER); IERC20Upgradeable(lpToken0).safeIncreaseAllowance( PROTOFI_ROUTER, lp0Allowance ); uint lp1Allowance = type(uint).max - IERC20Upgradeable(lpToken1).allowance(address(this), PROTOFI_ROUTER); IERC20Upgradeable(lpToken1).safeIncreaseAllowance( PROTOFI_ROUTER, lp1Allowance ); } /** * @dev Removes all allowance that were given */ function _removeAllowances() internal { IERC20Upgradeable(want).safeDecreaseAllowance(MASTER_CHEF, IERC20Upgradeable(want).allowance(address(this), MASTER_CHEF)); IERC20Upgradeable(PROTO).safeDecreaseAllowance(PROTOFI_ROUTER, IERC20Upgradeable(PROTO).allowance(address(this), PROTOFI_ROUTER)); IERC20Upgradeable(WFTM).safeDecreaseAllowance(PROTOFI_ROUTER, IERC20Upgradeable(WFTM).allowance(address(this), PROTOFI_ROUTER)); IERC20Upgradeable(lpToken0).safeDecreaseAllowance(PROTOFI_ROUTER, IERC20Upgradeable(lpToken0).allowance(address(this), PROTOFI_ROUTER)); IERC20Upgradeable(lpToken1).safeDecreaseAllowance(PROTOFI_ROUTER, IERC20Upgradeable(lpToken1).allowance(address(this), PROTOFI_ROUTER)); } }
Sets the minimum reward the will be sold (too little causes revert from Uniswap)/
function setMinProtoToSell(uint256 _minProtoToSell) external { _onlyStrategistOrOwner(); minProtoToSell = _minProtoToSell; }
1,757,654
pragma solidity ^0.5.0; import "./Bytes32SetLib.sol"; import "./BytesSetLib.sol"; import "./Bytes32DictionaryLib.sol"; import "./BytesDictionaryLib.sol"; import "./Bytes32SetDictionaryLib.sol"; import "./BytesSetDictionaryLib.sol"; /** * @title Polymorphic dictionary to store data. * @dev Polymorphic dictionary for managing * multiple dictionary types. * * Possible mappings are: * - bytes32 => bytes32 * - bytes32 => bytes * - bytes32 => { bytes32 } * - bytes32 => { bytes } * * Avoids key conflicts. * Stores data using Bytes32Set, BytesSet, Bytes32Dictionary, BytesDictionary * * - 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. * * Other primitive value types (uint256/int256/address/bool) can also be used as * converters are provided. * * @author Leo Vigna */ library PolymorphicDictionaryLib { //Sets using Bytes32SetLib for Bytes32SetLib.Bytes32Set; using BytesSetLib for BytesSetLib.BytesSet; //Bytes32 (Fixed) using Bytes32DictionaryLib for Bytes32DictionaryLib.Bytes32Dictionary; using Bytes32SetDictionaryLib for Bytes32SetDictionaryLib.Bytes32SetDictionary; //Bytes (Variable) using BytesDictionaryLib for BytesDictionaryLib.BytesDictionary; using BytesSetDictionaryLib for BytesSetDictionaryLib.BytesSetDictionary; struct PolymorphicDictionary { //One-to-one Bytes32DictionaryLib.Bytes32Dictionary OneToOneFixed; BytesDictionaryLib.BytesDictionary OneToOneVariable; //One-to-many Bytes32SetDictionaryLib.Bytes32SetDictionary OneToManyFixed; BytesSetDictionaryLib.BytesSetDictionary OneToManyVariable; } //Switch to Fixed/Var based on value override enum DictionaryType { OneToManyFixed, OneToManyVariable, OneToOneFixed, OneToOneVariable } // ****************************** ENUMERATE OPERATIONS ****************************** /** * @dev Enumerate all dictionary keys. O(n). * @param dictionary The PolymorphicDictionary. * @return bytes32[] dictionary keys. */ function enumerate(PolymorphicDictionary storage dictionary) internal view returns (bytes32[] memory) { bytes32[] memory keys0 = enumerate( dictionary, DictionaryType.OneToOneFixed ); bytes32[] memory keys1 = enumerate( dictionary, DictionaryType.OneToOneVariable ); bytes32[] memory keys2 = enumerate( dictionary, DictionaryType.OneToManyFixed ); bytes32[] memory keys3 = enumerate( dictionary, DictionaryType.OneToManyVariable ); bytes32[] memory keysAll = new bytes32[]( keys0.length + keys1.length + keys2.length + keys3.length ); uint256 idx = 0; for (uint256 i = 0; i < keys0.length; i++) { keysAll[idx] = keys0[i]; idx++; } for (uint256 i = 0; i < keys1.length; i++) { keysAll[idx] = keys1[i]; idx++; } for (uint256 i = 0; i < keys2.length; i++) { keysAll[idx] = keys2[i]; idx++; } for (uint256 i = 0; i < keys3.length; i++) { keysAll[idx] = keys3[i]; idx++; } return keysAll; } /** * @dev Enumerate dictionary keys based on storage type. O(n). * @param dictionary The PolymorphicDictionary. * @param _type The dictionary type. OneToManyFixed/OneToManyVariable/OneToOneFixed/OneToOneVariable * @return bytes32[] dictionary keys. */ function enumerate( PolymorphicDictionary storage dictionary, DictionaryType _type ) internal view returns (bytes32[] memory) { require(uint8(_type) < 4, "Invalid table type!"); if (DictionaryType.OneToManyFixed == _type) { return dictionary.OneToManyFixed.enumerateKeys(); } if (DictionaryType.OneToManyVariable == _type) { return dictionary.OneToManyVariable.enumerateKeys(); } if (DictionaryType.OneToOneFixed == _type) { return dictionary.OneToOneFixed.enumerateKeys(); } if (DictionaryType.OneToOneVariable == _type) { return dictionary.OneToOneVariable.enumerateKeys(); } } /** * @dev Enumerate dictionary set fixed values at dictionary[_key]. O(n). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @return bytes32[] values at key. */ function enumerateForKeyOneToManyFixed( PolymorphicDictionary storage dictionary, bytes32 _key ) internal view returns (bytes32[] memory) { return dictionary.OneToManyFixed.enumerateForKey(_key); } /** * @dev Enumerate dictionary set variable values at dictionary[_key]. O(n). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @return bytes[] values at key. */ function enumerateForKeyOneToManyVariable( PolymorphicDictionary storage dictionary, bytes32 _key ) internal view returns (bytes[] memory) { return dictionary.OneToManyVariable.enumerateForKey(_key); } // ****************************** CONTAINS OPERATIONS ****************************** /** * @dev Check if dictionary contains key. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @return true if key exists. */ function containsKey(PolymorphicDictionary storage dictionary, bytes32 _key) internal view returns (bool) { return dictionary.OneToOneFixed.containsKey(_key) || dictionary.OneToOneVariable.containsKey(_key) || dictionary.OneToManyFixed.containsKey(_key) || dictionary.OneToManyVariable.containsKey(_key); } /** * @dev Check if dictionary contains key based on storage type. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _type The dictionary type. OneToManyFixed/OneToManyVariable/OneToOneFixed/OneToOneVariable * @return true if key exists. */ function containsKey( PolymorphicDictionary storage dictionary, bytes32 _key, DictionaryType _type ) internal view returns (bool) { require(uint8(_type) < 4, "Invalid table type!"); if (DictionaryType.OneToManyFixed == _type) { return dictionary.OneToManyFixed.containsKey(_key); } if (DictionaryType.OneToManyVariable == _type) { return dictionary.OneToManyVariable.containsKey(_key); } if (DictionaryType.OneToOneFixed == _type) { return dictionary.OneToOneFixed.containsKey(_key); } if (DictionaryType.OneToOneVariable == _type) { return dictionary.OneToOneVariable.containsKey(_key); } } /** * @dev Check if dictionary contains fixed value at key. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The bytes32 value. * @return true if value exists at key. */ function containsValueForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bytes32 _value ) internal view returns (bool) { return dictionary.OneToManyFixed.containsValueForKey(_key, _value); } /** * @dev Check if dictionary contains variable value at key. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The bytes value. * @return true if value exists at key. */ function containsValueForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bytes memory _value ) internal view returns (bool) { return dictionary.OneToManyVariable.containsValueForKey(_key, _value); } // ****************************** LENGTH OPERATIONS ****************************** /** * @dev Get the number of keys in the dictionary. O(1). * @param dictionary The PolymorphicDictionary. * @return uint256 length. */ function length(PolymorphicDictionary storage dictionary) internal view returns (uint256) { return dictionary.OneToOneFixed.length() + dictionary.OneToOneVariable.length() + dictionary.OneToManyFixed.length() + dictionary.OneToManyVariable.length(); } /** * @dev Get the number of values at dictionary[_key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @return uint256 length. */ function lengthForKey( PolymorphicDictionary storage dictionary, bytes32 _key ) internal view returns (uint256) { return dictionary.OneToManyFixed.lengthForKey(_key) + dictionary.OneToManyVariable.lengthForKey(_key); } // ****************************** READ OPERATIONS ****************************** /** * @dev Get fixed value at dictionary[_key]. O(1). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return bytes32 value. */ function getBytes32ForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (bytes32) { return dictionary.OneToOneFixed.getValueForKey(key); } /** * @dev Get bool value at dictionary[_key]. O(1). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return bool value. */ function getBoolForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (bool) { return dictionary.OneToOneFixed.getValueForKey(key) != 0; } /** * @dev Get uint256 value at dictionary[_key]. O(1). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return uint256 value. */ function getUInt256ForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (uint256) { return uint256(dictionary.OneToOneFixed.getValueForKey(key)); } /** * @dev Get int256 value at dictionary[_key]. O(1). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return int256 value. */ function getInt256ForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (int256) { return int256(dictionary.OneToOneFixed.getValueForKey(key)); } /** * @dev Get address value at dictionary[_key]. O(1). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return address value. */ function getAddressForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (address) { return address( uint160(uint256(dictionary.OneToOneFixed.getValueForKey(key))) ); } /** * @dev Get variable value at dictionary[_key]. O(1). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return bytes value. */ function getBytesForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (bytes memory) { return dictionary.OneToOneVariable.getValueForKey(key); } /** * @dev Get Bytes32Set value set at dictionary[_key]. O(1). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return Bytes32Set value set. */ function getBytes32SetForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (Bytes32SetLib.Bytes32Set storage) { return dictionary.OneToManyFixed.getValueForKey(key); } /** * @dev Get BytesSet value set at dictionary[_key]. O(1). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return BytesSet value set. */ function getBytesSetForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (BytesSetLib.BytesSet storage) { return dictionary.OneToManyVariable.getValueForKey(key); } /** * @dev Get bytes32[] value array at dictionary[key]. O(dictionary[key].length()). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return bytes32[] value array. */ function getBytes32ArrayForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (bytes32[] memory) { Bytes32SetLib.Bytes32Set storage set = dictionary .OneToManyFixed .getValueForKey(key); uint256 len = set.length(); bytes32[] memory data = new bytes32[](len); for (uint256 i = 0; i < len; i++) { data[i] = set.get(i); } return data; } /** * @dev Get bool[] value array at dictionary[key]. O(dictionary[key].length()). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return bool[] value array. */ function getBoolArrayForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (bool[] memory) { Bytes32SetLib.Bytes32Set storage set = dictionary .OneToManyFixed .getValueForKey(key); uint256 len = set.length(); bool[] memory data = new bool[](len); for (uint256 i = 0; i < len; i++) { data[i] = set.get(i) != 0; } return data; } /** * @dev Get uint256[] value array at dictionary[key]. O(dictionary[key].length()). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return uint256[] value array. */ function getUIntArrayForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (uint256[] memory) { Bytes32SetLib.Bytes32Set storage set = dictionary .OneToManyFixed .getValueForKey(key); uint256 len = set.length(); uint256[] memory data = new uint256[](len); for (uint256 i = 0; i < len; i++) { data[i] = uint256(set.get(i)); } return data; } /** * @dev Get int256[] value array at dictionary[key]. O(dictionary[key].length()). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return int256[] value array. */ function getIntArrayForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (int256[] memory) { Bytes32SetLib.Bytes32Set storage set = dictionary .OneToManyFixed .getValueForKey(key); uint256 len = set.length(); int256[] memory data = new int256[](len); for (uint256 i = 0; i < len; i++) { data[i] = int256(set.get(i)); } return data; } /** * @dev Get address[] value array at dictionary[key]. O(dictionary[key].length()). * @param dictionary The PolymorphicDictionary. * @param key The bytes32 key. * @return address[] value array. */ function getAddressArrayForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (address[] memory) { Bytes32SetLib.Bytes32Set storage set = dictionary .OneToManyFixed .getValueForKey(key); uint256 len = set.length(); address[] memory data = new address[](len); for (uint256 i = 0; i < len; i++) { data[i] = address(uint160(uint256(set.get(i)))); } return data; } // ****************************** WRITE OPERATIONS ****************************** // ****************************** SET VALUE ****************************** /** * @dev Set fixed value at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The bytes32 value. * @return bool true if succeeded (no conflicts). */ function setValueForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bytes32 _value ) internal returns (bool) { require( !dictionary.OneToOneVariable.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToManyFixed.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToManyVariable.containsKey(_key), "Error: key exists in other dict." ); return dictionary.OneToOneFixed.setValueForKey(_key, _value); } /** * @dev Set bool value at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The bool value. * @return bool true if succeeded (no conflicts). */ function setBoolForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bool _value ) internal returns (bool) { if (_value) { return setValueForKey(dictionary, _key, bytes32(uint256(1))); } else { return setValueForKey(dictionary, _key, bytes32(uint256(0))); } } /** * @dev Set uint value at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The uint value. * @return bool true if succeeded (no conflicts). */ function setUIntForKey( PolymorphicDictionary storage dictionary, bytes32 _key, uint256 _value ) internal returns (bool) { return setValueForKey(dictionary, _key, bytes32(_value)); } /** * @dev Set int value at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The int value. * @return bool true if succeeded (no conflicts). */ function setIntForKey( PolymorphicDictionary storage dictionary, bytes32 _key, int256 _value ) internal returns (bool) { return setValueForKey(dictionary, _key, bytes32(_value)); } /** * @dev Set address value at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The address value. * @return bool true if succeeded (no conflicts). */ function setAddressForKey( PolymorphicDictionary storage dictionary, bytes32 _key, address _value ) internal returns (bool) { return setValueForKey(dictionary, _key, bytes32(uint256(_value))); } /** * @dev Set variable value at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The bytes value. * @return bool true if succeeded (no conflicts). */ function setValueForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bytes memory _value ) internal returns (bool) { require( !dictionary.OneToOneFixed.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToManyFixed.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToManyVariable.containsKey(_key), "Error: key exists in other dict." ); return dictionary.OneToOneVariable.setValueForKey(_key, _value); } // ****************************** ADD VALUE ****************************** /** * @dev Add fixed value to set at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The bytes32 value. * @return bool true if succeeded (no conflicts). */ function addValueForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bytes32 _value ) internal returns (bool) { require( !dictionary.OneToOneFixed.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToOneVariable.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToManyVariable.containsKey(_key), "Error: key exists in other dict." ); return dictionary.OneToManyFixed.addValueForKey(_key, _value); } /** * @dev Add bool value to set at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The bool value. * @return bool true if succeeded (no conflicts). */ function addBoolForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bool _value ) internal returns (bool) { if (_value) { return addValueForKey(dictionary, _key, bytes32(uint256(1))); } else { return addValueForKey(dictionary, _key, bytes32(uint256(0))); } } /** * @dev Add uint value to set at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The uint value. * @return bool true if succeeded (no conflicts). */ function addUIntForKey( PolymorphicDictionary storage dictionary, bytes32 _key, uint256 _value ) internal returns (bool) { return addValueForKey(dictionary, _key, bytes32(_value)); } /** * @dev Add int value to set at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The int value. * @return bool true if succeeded (no conflicts). */ function addIntForKey( PolymorphicDictionary storage dictionary, bytes32 _key, int256 _value ) internal returns (bool) { return addValueForKey(dictionary, _key, bytes32(_value)); } /** * @dev Add address value to set at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The address value. * @return bool true if succeeded (no conflicts). */ function addAddressForKey( PolymorphicDictionary storage dictionary, bytes32 _key, address _value ) internal returns (bool) { return addValueForKey(dictionary, _key, bytes32(uint256(_value))); } /** * @dev Add variable value to set at dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The variable value. * @return bool true if succeeded (no conflicts). */ function addValueForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bytes memory _value ) internal returns (bool) { require( !dictionary.OneToOneFixed.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToOneVariable.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToManyFixed.containsKey(_key), "Error: key exists in other dict." ); return dictionary.OneToManyVariable.addValueForKey(_key, _value); } // ****************************** ADD/REMOVE KEYS ****************************** /** * @dev Add key (no value) to dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _type The dictionary type. OneToManyFixed/OneToManyVariable/OneToOneFixed/OneToOneVariable * @return bool true if succeeded (no conflicts). */ function addKey( PolymorphicDictionary storage dictionary, bytes32 _key, DictionaryType _type ) internal returns (bool) { require(uint8(_type) < 4, "Invalid table type!"); require( !dictionary.OneToOneFixed.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToOneVariable.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToManyFixed.containsKey(_key), "Error: key exists in other dict." ); require( !dictionary.OneToManyVariable.containsKey(_key), "Error: key exists in other dict." ); if (DictionaryType.OneToManyFixed == _type) { return dictionary.OneToManyFixed.addKey(_key); } if (DictionaryType.OneToManyVariable == _type) { return dictionary.OneToManyVariable.addKey(_key); } if (DictionaryType.OneToOneFixed == _type) { return dictionary.OneToOneFixed.setValueForKey( _key, 0x0000000000000000000000000000000000000000000000000000000000000000 ); } if (DictionaryType.OneToOneVariable == _type) { return dictionary.OneToOneVariable.setValueForKey(_key, new bytes(0)); } } /** * @dev Remove key from dictionary[key]. O(1). * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @return bool true if succeeded (no conflicts). */ function removeKey(PolymorphicDictionary storage dictionary, bytes32 _key) internal returns (bool) { return dictionary.OneToOneFixed.removeKey(_key) || dictionary.OneToOneVariable.removeKey(_key) || dictionary.OneToManyFixed.removeKey(_key) || dictionary.OneToManyVariable.removeKey(_key); } /** * @dev Remove fixed value from set at dictionary[key]. * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The bytes32 value. * @return bool true if succeeded (no conflicts). */ function removeValueForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bytes32 _value ) internal returns (bool) { return dictionary.OneToManyFixed.removeValueForKey(_key, _value); } /** * @dev Remove variable value from set at dictionary[key]. * @param dictionary The PolymorphicDictionary. * @param _key The bytes32 key. * @param _value The bytes value. * @return bool true if succeeded (no conflicts). */ function removeValueForKey( PolymorphicDictionary storage dictionary, bytes32 _key, bytes memory _value ) internal returns (bool) { return dictionary.OneToManyVariable.removeValueForKey(_key, _value); } }
Get int256 value at dictionary[_key]. O(1). dictionary The PolymorphicDictionary. key The bytes32 key. return int256 value./
function getInt256ForKey( PolymorphicDictionary storage dictionary, bytes32 key ) internal view returns (int256) { return int256(dictionary.OneToOneFixed.getValueForKey(key)); }
14,123,676
/** *Submitted for verification at Etherscan.io on 2020-07-07 */ // File: localhost/mcd/maker/Manager.sol pragma solidity ^0.6.0; abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } // File: localhost/mcd/maker/Vat.sol pragma solidity ^0.6.0; abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } // File: localhost/shifter/LoanShifterTaker.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // import "../interfaces/ILendingPool.sol"; // import "../interfaces/CTokenInterface.sol"; // import "../interfaces/ILoanShifter.sol"; // import "../interfaces/DSProxyInterface.sol"; // import "../auth/AdminAuth.sol"; // import "../auth/ProxyPermission.sol"; // import "../loggers/FlashLoanLogger.sol"; // import "../utils/ExchangeDataParser.sol"; // import "../exchange/SaverExchangeCore.sol"; /// @title LoanShifterTaker Entry point for using the shifting operation contract LoanShifterTaker // is AdminAuth, ProxyPermission { // ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; // address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // address public constant cDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; // address payable public constant LOAN_SHIFTER_RECEIVER = 0xA94B7f0465E98609391C623d0560C5720a3f2D33; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(MANAGER_ADDRESS); enum Protocols { MCD, COMPOUND, AAVE } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr; address addrLoan1; address addrLoan2; uint id1; uint id2; } // mapping (Protocols => address) public contractAddresses; /// @notice Main entry point, it will move or transform a loan /// @dev If the operation doesn't require exchange send empty data function moveLoan( LoanShiftData memory _loanShift //, // SaverExchangeCore.ExchangeData memory _exchangeData ) public { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } // _callCloseAndOpen(_loanShift, _exchangeData); } /// @notice An admin only function to add/change a protocols address // function addProtocol(uint8 _protoType, address _protoAddr) public onlyOwner { // contractAddresses[Protocols(_protoType)] = _protoAddr; // } // function getProtocolAddr(Protocols _proto) public view returns (address) { // return contractAddresses[_proto]; // } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// // function _callCloseAndOpen( // LoanShiftData memory _loanShift, // SaverExchangeCore.ExchangeData memory _exchangeData // ) internal { // address protoAddr = getProtocolAddr(_loanShift.fromProtocol); // uint loanAmount = _loanShift.debtAmount; // if (_loanShift.wholeDebt) { // loanAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.addrLoan1); // } // ( // uint[8] memory numData, // address[6] memory addrData, // uint8[3] memory enumData, // bytes memory callData // ) // = _packData(_loanShift, _exchangeData); // // encode data // bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); // // call FL // givePermission(LOAN_SHIFTER_RECEIVER); // lendingPool.flashLoan(LOAN_SHIFTER_RECEIVER, _loanShift.debtAddr, loanAmount, paramsData); // removePermission(LOAN_SHIFTER_RECEIVER); // } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } else { Vat(VAT_ADDRESS).fork( manager.ilks(_loanShift.id1), manager.urns(_loanShift.id1), manager.urns(_loanShift.id2), int(_loanShift.collAmount), int(_loanShift.debtAmount) ); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } // function _packData( // LoanShiftData memory _loanShift, // SaverExchangeCore.ExchangeData memory exchangeData // ) internal pure returns (uint[8] memory numData, address[6] memory addrData, uint8[3] memory enumData, bytes memory callData) { // numData = [ // _loanShift.collAmount, // _loanShift.debtAmount, // _loanShift.id1, // _loanShift.id2, // exchangeData.srcAmount, // exchangeData.destAmount, // exchangeData.minPrice, // exchangeData.price0x // ]; // addrData = [ // _loanShift.addrLoan1, // _loanShift.addrLoan2, // _loanShift.debtAddr, // exchangeData.srcAddr, // exchangeData.destAddr, // exchangeData.exchangeAddr // ]; // enumData = [ // uint8(_loanShift.fromProtocol), // uint8(_loanShift.toProtocol), // uint8(exchangeData.exchangeType) // ]; // callData = exchangeData.callData; // } }
File: localhost/shifter/LoanShifterTaker.sol import "../interfaces/ILendingPool.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/ILoanShifter.sol"; import "../interfaces/DSProxyInterface.sol"; import "../auth/AdminAuth.sol"; import "../auth/ProxyPermission.sol"; import "../loggers/FlashLoanLogger.sol"; import "../utils/ExchangeDataParser.sol"; import "../exchange/SaverExchangeCore.sol"; LoanShifterTaker Entry point for using the shifting operation ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant cDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address payable public constant LOAN_SHIFTER_RECEIVER = 0xA94B7f0465E98609391C623d0560C5720a3f2D33;
{ address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(MANAGER_ADDRESS); enum Protocols { MCD, COMPOUND, AAVE } function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr; address addrLoan1; address addrLoan2; uint id1; uint id2; } function moveLoan( ) public { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } function moveLoan( ) public { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } } function _forkVault(LoanShiftData memory _loanShift) internal { if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); Vat(VAT_ADDRESS).fork( manager.ilks(_loanShift.id1), manager.urns(_loanShift.id1), manager.urns(_loanShift.id2), int(_loanShift.collAmount), int(_loanShift.debtAmount) ); } } function _forkVault(LoanShiftData memory _loanShift) internal { if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); Vat(VAT_ADDRESS).fork( manager.ilks(_loanShift.id1), manager.urns(_loanShift.id1), manager.urns(_loanShift.id2), int(_loanShift.collAmount), int(_loanShift.debtAmount) ); } } function _forkVault(LoanShiftData memory _loanShift) internal { if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); Vat(VAT_ADDRESS).fork( manager.ilks(_loanShift.id1), manager.urns(_loanShift.id1), manager.urns(_loanShift.id2), int(_loanShift.collAmount), int(_loanShift.debtAmount) ); } } } else { function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } }
10,983,228
./full_match/137/0x38cFB3508A0ED15AFf3C2316B586608d0d6b8C1f/sources/contracts/Core.sol
Core Functions / setup the game and triger to start it
function startGame() external override onlyDeployer returns (bool) { RoundInfo storage round = rounds[currentRoundID]; require(currentRoundID == 0, "only can be triggered once"); require(round.status == 0, "only when not initialized"); round.initTime = block.timestamp; round.initPrice = rate(); round.status = 1; isStarted = true; return true; }
4,692,018
pragma solidity ^0.5.10; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; interface IStatelessSwap { event ListingActive( bytes32 indexed _listingID, address indexed _seller, address indexed _asset, uint256 _value, bytes _partialTx, uint256 _reqDiff ); event ListingClosed( bytes32 indexed _listingID, address _seller, address indexed _bidder, address indexed _asset, uint256 _value ); /// @notice Seller opens listing by committing ethereum /// @param _partialTx Seller's partial transaction /// @param _reqDiff Minimum acceptable block difficulty summation /// @param _asset The address of the asset contract. address(0) for ETH /// @param _value The amount of asset for sale, in smallest possible units /// @return true if Seller post is valid, false otherwise function open( bytes calldata _partialTx, uint256 _reqDiff, address _asset, uint256 _value ) external payable returns (bytes32); /// @notice Validate selected bid, bidder claims eth /// @param _version The 4-byte tx version /// @param _vin The length-prepended tx input vector /// @param _vout The length-prepended tx output vector /// @param _locktime The 4-byte tx locktime /// @param _proof The merkle proof of inclusion /// @param _index Merkle proof leaf index to aid verification /// @param _headers The raw bytes of all headers in order from earliest to latest /// @return true if bid is successfully accepted, error otherwise function claim( bytes calldata _proof, uint _index, bytes calldata _version, bytes calldata _vin, bytes calldata _vout, bytes calldata _locktime, bytes calldata _headers ) external returns (bool); /// @notice Validates the submitted bid transaction /// @dev Uses bitcoin parsing tools. This could be made more gas efficient /// @param _version The 4-byte tx version /// @param _vin The length-prepended tx input vector /// @param _vout The length-prepended tx output vector /// @param _locktime The 4-byte tx locktime /// @return The txid function checkTx( bytes calldata _version, bytes calldata _vin, bytes calldata _vout, bytes calldata _locktime ) external pure returns (bytes32 _txid); /// @notice Validates submitted header chain /// @dev Checks that all headers are linked, that each meets its target difficulty /// @param _headers The raw byte header chain /// @return The total difficulty of the header chain, and the first header's tx tree root function checkHeaders( bytes calldata _headers ) external view returns (uint256 _diff, bytes32 _merkleRoot); /// @notice Validates submitted merkle inclusion proof /// @dev Takes in the x /// @param _txid The 32 byte txid /// @param _merkleRoot The block header's merkle root /// @param _proof The inclusion proof /// @param _index The index of the txid in the leaf set /// @return true if _proof and _index show that _txid is in the _merkleRoot, else false function checkProof( bytes32 _txid, bytes32 _merkleRoot, bytes calldata _proof, uint256 _index ) external pure returns (bool); } contract StatelessSwap is IStatelessSwap { using BTCUtils for bytes; using BTCUtils for uint256; using BytesLib for bytes; using SafeMath for uint256; using ValidateSPV for bytes; using ValidateSPV for bytes32; enum ListingStates { NONE, ACTIVE, CLOSED } struct Listing { ListingStates state; uint256 value; // Asset amount or 721 ID uint256 reqDiff; // Required number of difficulty in confirmed blocks address asset; // Asset info address seller; // Seller address address wrapper; // The new NoFun (if applicable) // Filled Later address bidder; // Accepted bidder address bytes32 txid; // Accepted tx hash } address payable public developer; mapping(bytes32 => Listing) public listings; constructor (address _developer) public { developer = address(uint160(_developer)); } // IMPLEMENT FOR SPECIFIC ASSET TYPES function ensureFunding(Listing storage _listing) internal; function distribute(Listing storage _listing) internal; /// @notice Seller opens listing by committing ethereum /// @param _partialTx Seller's partial transaction /// @param _reqDiff Minimum acceptable block difficulty summation /// @param _asset The address of the asset contract. address(0) for ETH /// @param _value The amount of asset for sale, in smallest possible units /// @return true if Seller post is valid, false otherwise function open( bytes calldata _partialTx, uint256 _reqDiff, address _asset, uint256 _value ) external payable returns (bytes32) { // Listing identifier is keccak256 of Seller's partial transaction outpoint bytes32 _listingID = keccak256(_partialTx.slice(7, 36)); // Require unique listing identifier require(listings[_listingID].state == ListingStates.NONE, "Listing exists."); // Add to listings mapping listings[_listingID].state = ListingStates.ACTIVE; listings[_listingID].value = _value; if (_asset != address(0)) { listings[_listingID].asset = _asset; } listings[_listingID].seller = msg.sender; listings[_listingID].reqDiff = _reqDiff; ensureFunding(listings[_listingID]); // Emit ListingActive event emit ListingActive( _listingID, msg.sender, _asset, _value, _partialTx, _reqDiff); return _listingID; } /// @notice Validate selected bid, bidder claims eth /// @param _proof The merkle proof of inclusion /// @param _index Merkle proof leaf index to aid verification /// @param _version The 4-byte tx version /// @param _vin The length-prepended tx input vector /// @param _vout The length-prepended tx output vector /// @param _locktime The 4-byte tx locktime /// @param _headers The raw bytes of all headers in order from earliest to latest /// @return true if bid is successfully accepted, error otherwise function claim( bytes calldata _proof, uint _index, bytes calldata _version, bytes calldata _vin, bytes calldata _vout, bytes calldata _locktime, bytes calldata _headers ) external returns (bool) { uint256 _diff = _makeAllChecks( _proof, _index, _version, _vin, _vout, _locktime, _headers); bytes32 _listingID = keccak256(_vin.slice(1, 36)); Listing storage _listing = listings[_listingID]; // Require listing state to be ACTIVE and difficulty to be sufficient require(_diff >= _listing.reqDiff, "Not enough difficulty in header chain."); require(_listing.state == ListingStates.ACTIVE, "Listing has closed or does not exist."); address _bidder = _extractBidder(_vout); if (_bidder == address(0)) { _bidder = _listing.seller; } // Update listing state _listing.bidder = _bidder; _listing.state = ListingStates.CLOSED; distribute(_listing); // Emit ListingClosed event emit ListingClosed( _listingID, _listing.seller, _listing.bidder, _listing.asset, _listing.value ); return true; } /// @notice Extracts the bidder address from the bid tx /// @dev Returns 0 if the op_return is weird or there's only 1 output /// @param _vout The length-prefixed transaction output vector /// @return The 20 byte bidder address from the op_return, or address(0) function _extractBidder(bytes memory _vout) internal pure returns (address _bidder) { _bidder = address(0); if (uint8(_vout[0]) > 1) { bytes memory _data = _vout.extractOutputAtIndex(1).extractOpReturnData(); _bidder = _data.length >= 20 ? _data.toAddress(0) : address(0); } } /// @notice Extracts the bidder address from the bid tx /// @dev Returns 0 if the op_return is weird or there's only 1 output /// @param _vout The length-prefixed transaction output vector /// @return The 20 byte bidder address from the op_return, or address(0) function extractBidder(bytes calldata _vout) external pure returns (address _bidder) { return _extractBidder(_vout); } /// @notice Validate everything about an spv proof /// @param _proof The merkle proof of inclusion /// @param _index Merkle proof leaf index to aid verification /// @param _version The 4-byte tx version /// @param _vin The length-prepended tx input vector /// @param _vout The length-prepended tx output vector /// @param _locktime The 4-byte tx locktime /// @param _headers The raw bytes of all headers in order from earliest to latest /// @return The difficulty of the header chain, or error if there was an issue function _makeAllChecks( bytes memory _proof, uint _index, bytes memory _version, bytes memory _vin, bytes memory _vout, bytes memory _locktime, bytes memory _headers ) internal view returns (uint256 _diff) { bytes32 _merkleRoot; bytes32 _txid = _checkTx(_version, _vin, _vout, _locktime); (_diff, _merkleRoot) = _checkHeaders(_headers); _checkProof(_txid, _merkleRoot, _proof, _index); } /// @notice Validate everything about an spv proof /// @param _proof The merkle proof of inclusion /// @param _index Merkle proof leaf index to aid verification /// @param _version The 4-byte tx version /// @param _vin The length-prepended tx input vector /// @param _vout The length-prepended tx output vector /// @param _locktime The 4-byte tx locktime /// @param _headers The raw bytes of all headers in order from earliest to latest /// @return The difficulty of the header chain, or error if there was an issue function makeAllChecks( bytes calldata _proof, uint _index, bytes calldata _version, bytes calldata _vin, bytes calldata _vout, bytes calldata _locktime, bytes calldata _headers ) external view returns (uint256 _diff) { return _makeAllChecks(_proof, _index, _version, _vin, _vout, _locktime, _headers); } /// @notice Validates the submitted bid transaction /// @dev Uses bitcoin parsing tools. This could be made more gas efficient /// @param _version The 4-byte tx version /// @param _vin The length-prepended tx input vector /// @param _vout The length-prepended tx output vector /// @param _locktime The 4-byte tx locktime /// @return The txid function _checkTx( bytes memory _version, bytes memory _vin, bytes memory _vout, bytes memory _locktime ) internal pure returns (bytes32 _txid) { require(_vin.validateVin(), "vin is malformed"); require(_vout.validateVout(), "vout is malformed"); _txid = ValidateSPV.calculateTxId(_version, _vin, _vout, _locktime); } /// @notice Validates the submitted bid transaction /// @dev Uses bitcoin parsing tools. This could be made more gas efficient /// @param _version The 4-byte tx version /// @param _vin The length-prepended tx input vector /// @param _vout The length-prepended tx output vector /// @param _locktime The 4-byte tx locktime /// @return The txid, the bidder's ethereum address, and the value of the first output function checkTx( bytes calldata _version, bytes calldata _vin, bytes calldata _vout, bytes calldata _locktime ) external pure returns (bytes32 _txid) { return _checkTx(_version, _vin, _vout, _locktime); } /// @notice Validates submitted header chain /// @dev Checks that all headers are linked, that each meets its target difficulty /// @param _headers The raw byte header chain /// @return The total difficulty of the header chain, and the first header's tx tree root function _checkHeaders( bytes memory _headers ) internal view returns (uint256 _diff, bytes32 _merkleRoot) { _diff = _headers.validateHeaderChain(); require(_diff != ValidateSPV.getErrBadLength(), "Header bytes not multiple of 80."); require(_diff != ValidateSPV.getErrInvalidChain(), "Header bytes not a valid chain."); require(_diff != ValidateSPV.getErrLowWork(), "Header does not meet its own difficulty target."); _merkleRoot = _headers.extractMerkleRootLE().toBytes32(); } /// @notice Validates submitted header chain /// @dev Checks that all headers are linked, that each meets its target difficulty /// @param _headers The raw byte header chain /// @return The total difficulty of the header chain, and the first header's tx tree root function checkHeaders( bytes calldata _headers ) external view returns (uint256 _diff, bytes32 _merkleRoot) { return _checkHeaders(_headers); } /// @notice Validates submitted merkle inclusion proof /// @dev Takes in the x /// @param _txid The 32 byte txid /// @param _merkleRoot The block header's merkle root /// @param _proof The inclusion proof /// @param _index The index of the txid in the leaf set /// @return true if _proof and _index show that _txid is in the _merkleRoot, else false function _checkProof( bytes32 _txid, bytes32 _merkleRoot, bytes memory _proof, uint256 _index ) internal pure returns (bool) { require(_txid.prove(_merkleRoot, _proof, _index), "Bad inclusion proof"); return true; } /// @notice Validates submitted merkle inclusion proof /// @dev Takes in the x /// @param _txid The 32 byte txid /// @param _merkleRoot The block header's merkle root /// @param _proof The inclusion proof /// @param _index The index of the txid in the leaf set /// @return true if _proof and _index show that _txid is in the _merkleRoot, else false function checkProof( bytes32 _txid, bytes32 _merkleRoot, bytes calldata _proof, uint256 _index ) external pure returns (bool) { return _checkProof(_txid, _merkleRoot, _proof, _index); } /// @notice Calculates the developer's fee /// @dev Looks up the listing and calculates a 25bps fee. Do not use for erc721. /// @param _value The amount of value to split between bidder and developer /// @return The fee share and the bidder's share function _allocate(uint256 _value) internal pure returns (uint256, uint256) { // developer share uint256 _feeShare = _value.div(400); // Bidder share uint256 _bidderShare = _value.sub(_feeShare); return (_feeShare, _bidderShare); } /// @notice Calculates the developer's fee /// @dev Looks up the listing and calculates a 25bps fee. Do not use for erc721. /// @param _value The amount of value to split between bidder and developer /// @return The fee share and the bidder's share function allocate(uint256 _value) external pure returns (uint256, uint256) { return _allocate(_value); } }
Validate everything about an spv proof _proof The merkle proof of inclusion _index Merkle proof leaf index to aid verification _version The 4-byte tx version _vin The length-prepended tx input vector _vout The length-prepended tx output vector _locktime The 4-byte tx locktime _headers The raw bytes of all headers in order from earliest to latest return The difficulty of the header chain, or error if there was an issue
function _makeAllChecks( bytes memory _proof, uint _index, bytes memory _version, bytes memory _vin, bytes memory _vout, bytes memory _locktime, bytes memory _headers ) internal view returns (uint256 _diff) { bytes32 _merkleRoot; bytes32 _txid = _checkTx(_version, _vin, _vout, _locktime); (_diff, _merkleRoot) = _checkHeaders(_headers); _checkProof(_txid, _merkleRoot, _proof, _index); }
12,787,578
pragma solidity ^0.4.15; contract Factory{ //Adress of creator address private creator; // Addresses of owners address private owner1 = 0x6CAa636cFFbCbb2043A3322c04dE3f26b1fa6555; address private owner2 = 0xbc2d90C2D3A87ba3fC8B23aA951A9936A6D68121; address private owner3 = 0x680d821fFE703762E7755c52C2a5E8556519EEDc; //List of deployed Forwarders address[] public deployed_forwarders; //Get number of forwarders created uint public forwarders_count = 0; //Last forwarder create address public last_forwarder_created; //Only owners can generate a forwarder modifier onlyOwnerOrCreator { require(msg.sender == owner1 || msg.sender == owner2 || msg.sender == owner3 || msg.sender == creator); _; } //Constructor constructor() public { creator = msg.sender; } //Create new Forwarder function create_forwarder() public onlyOwnerOrCreator { address new_forwarder = new Forwarder(); deployed_forwarders.push(new_forwarder); last_forwarder_created = new_forwarder; forwarders_count += 1; } //Get deployed forwarders function get_deployed_forwarders() public view returns (address[]) { return deployed_forwarders; } } contract Forwarder { // Address to which any funds sent to this contract will be forwarded address private parentAddress = 0x7aeCf441966CA8486F4cBAa62fa9eF2D557f9ba7; // Addresses of people who can flush ethers and tokenContractAddress address private owner1 = 0x6CAa636cFFbCbb2043A3322c04dE3f26b1fa6555; address private owner2 = 0xbc2d90C2D3A87ba3fC8B23aA951A9936A6D68121; address private owner3 = 0x680d821fFE703762E7755c52C2a5E8556519EEDc; event ForwarderDeposited(address from, uint value, bytes data); /** * Create the contract. */ constructor() public { } /** * Modifier that will execute internal code block only if the sender is among owners. */ modifier onlyOwner { require(msg.sender == owner1 || msg.sender == owner2 || msg.sender == owner3); _; } /** * Default function; Gets called when Ether is deposited, and forwards it to the parent address */ function() public payable { // throws on failure parentAddress.transfer(msg.value); // Fire off the deposited event if we can forward it emit ForwarderDeposited(msg.sender, msg.value, msg.data); } /** * Execute a token transfer of the full balance from the forwarder token to the parent address * @param tokenContractAddress the address of the erc20 token contract */ function flushTokens(address tokenContractAddress) public onlyOwner { ERC20Interface instance = ERC20Interface(tokenContractAddress); address forwarderAddress = address(this); uint forwarderBalance = instance.balanceOf(forwarderAddress); if (forwarderBalance == 0) { return; } if (!instance.transfer(parentAddress, forwarderBalance)) { revert(); } } /** * It is possible that funds were sent to this address before the contract was deployed. * We can flush those funds to the parent address. */ function flush() public onlyOwner { // throws on failure uint my_balance = address(this).balance; if (my_balance == 0){ return; } else { parentAddress.transfer(address(this).balance); } } } contract ERC20Interface { // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); }
Create new Forwarder
function create_forwarder() public onlyOwnerOrCreator { address new_forwarder = new Forwarder(); deployed_forwarders.push(new_forwarder); last_forwarder_created = new_forwarder; forwarders_count += 1; }
10,468,689
/** *Submitted for verification at Etherscan.io on 2020-09-30 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.6; 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); event Burn(address indexed from, uint256 value); } interface ERC223 { function transfer(address to, uint value, bytes calldata data) external returns(bool); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } interface ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes calldata _data) external; } 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) { uint256 c = a / b; 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; } } 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.3._ */ 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.3._ */ 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); } } } } 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; } } 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 () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @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()); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract TokenContract is IERC20, Pausable,ERC223 { using SafeMath for uint256; string internal _name; string internal _symbol; uint8 internal _decimals; uint256 internal _totalSupply; address internal _admin; uint256 private tokenSold; uint256 internal lockedBalance; event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); event transferredOwnership (address indexed previousOwner,address indexed currentOwner); uint256 private _totalShares; uint256 private _totalReleased; address[] internal _payees; struct vestingDetails { address user; uint256 amount; uint256 startTime; uint256 endTime; bool vestingStatus; } mapping(address => uint256) private _shares; mapping(address => uint256) private _released; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; mapping (address=> vestingDetails) internal vesting; constructor() public { _admin = msg.sender; _symbol = "NBK"; _name = "Notebook"; _decimals = 18; _totalSupply = 98054283* 10**uint(_decimals); balances[msg.sender]=_totalSupply; } modifier ownership() { require(msg.sender == _admin); _; } function name() public view returns (string memory) { return _name; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function symbol() public view returns (string memory) { return _symbol; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function _tokenSold() public view returns(uint256) { return tokenSold; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function decimals() public view returns (uint8) { return _decimals; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function totalSupply() public override view returns (uint256) { return _totalSupply; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function transfer(address _to, uint256 _value) public virtual override returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balances[msg.sender] = balances[msg.sender].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balances[_to] = (balances[_to]).add( _value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit IERC20.Transfer(msg.sender, _to, _value); tokenSold += _value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function balanceOf(address _owner) public override view returns (uint256 balance) { return balances[_owner]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(_value <= allowed[_from][msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balances[_from] = (balances[_from]).sub( _value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balances[_to] = (balances[_to]).add(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC tokenSold += _value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit IERC20.Transfer(_from, _to, _value); return true; } function openVesting(address _user,uint256 _amount, uint256 _eTime) ownership public returns(bool) { lockTokens(_amount); vesting[_user].user = _user; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC vesting[_user].amount= _amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC vesting[_user].startTime = now; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC vesting[_user].endTime = _eTime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC vesting[_user].vestingStatus = true; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function releaseVesting(address _user) ownership public returns(bool) { require(now > vesting[_user].endTime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC vesting[_user].vestingStatus = false; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC unlockTokens(vesting[_user].amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function approve(address _spender, uint256 _value) public override returns (bool) { allowed[msg.sender][_spender] = _value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit IERC20.Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public override view returns (uint256) { return allowed[_owner][_spender]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function burn(uint256 _value) public ownership returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balances[msg.sender] -= _value; // Subtract from the sender //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _totalSupply -= _value; // Updates totalSupply //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC //emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account */ function burnFrom(address _from, uint256 _value) public ownership returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(_value <= allowed[_from][msg.sender]); // Check allowance //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balances[_from] -= _value; // Subtract from the targeted balance //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _totalSupply -= _value; // Update totalSupply //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // emit Burn(_from, _value); return true; } //Admin can transfer his ownership to new address function transferownership(address _newaddress) ownership public returns(bool){ require(_newaddress != address(0)); emit transferredOwnership(_admin, _newaddress); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _admin=_newaddress; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function ownerAddress() public view returns(address) { return _admin; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function totalShares() public view returns (uint256) { return _totalShares; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } receive () external payable virtual { emit PaymentReceived(msg.sender, msg.value); } function distributeEthersToHolders (address[] memory payees, uint256[] memory amountOfEther) public payable { // solhint-disable-next-line max-line-length require(payees.length == amountOfEther.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], amountOfEther[i]); } } function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares.add(shares_); emit PayeeAdded(account, shares_); } function releaseEthersToHolder(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 totalReceived = address(this).balance.add(_totalReleased); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 payment = totalReceived.mul(_shares[account]).div(_totalShares).sub(_released[account]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account].add(payment); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _totalReleased = _totalReleased.add(payment); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC account.transfer(payment); emit PaymentReleased(account, payment); } function pauseToken() public ownership whenNotPaused { _pause(); } function unPauseToken() public ownership whenPaused { _unpause(); } function transfer(address _to, uint _value, bytes memory _data) public virtual override returns (bool ){ require(_value > 0 ); if(isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } balances[msg.sender] = balances[msg.sender].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balances[_to] = (balances[_to]).add( _value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit Transfer(msg.sender, _to, _value, _data); return true; } function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } function lockTokens(uint256 _amount) ownership public returns(bool){ require( balances[_admin]>=_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balances[_admin] = balances[_admin].sub(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC lockedBalance = lockedBalance.add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function unlockTokens(uint256 _amount) ownership public returns (bool) { require(lockedBalance >= _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balances[_admin] = balances[_admin].add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC lockedBalance = lockedBalance.sub(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function viewLockedBalance() ownership public view returns(uint256) { return lockedBalance; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } contract NBK is TokenContract { constructor () public { } function transfer(address _to, uint256 _amount) public whenNotPaused override returns(bool) { return super.transfer(_to,_amount); } function transferFrom(address _from, address _to, uint256 _amount) public whenNotPaused override returns(bool) { return super.transferFrom(_from,_to,_amount); } }
Getter for the total amount of Ether already released./
function totalReleased() public view returns (uint256) { }
12,989,949
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; import "./utils/ReentrancyGuard.sol"; import "./markets/MarketRegistry.sol"; import "./SpecialTransferHelper.sol"; import "../../interfaces/markets/tokens/IERC20.sol"; import "../../interfaces/markets/tokens/IERC721.sol"; import "../../interfaces/markets/tokens/IERC1155.sol"; contract GemSwap is SpecialTransferHelper, Ownable, ReentrancyGuard { struct OpenseaTrades { uint256 value; bytes tradeData; } struct ERC20Details { address[] tokenAddrs; uint256[] amounts; } struct ERC1155Details { address tokenAddr; uint256[] ids; uint256[] amounts; } struct ConverstionDetails { bytes conversionData; } struct AffiliateDetails { address affiliate; bool isActive; } struct SponsoredMarket { uint256 marketId; bool isActive; } address public constant GOV = 0x83d841bC0450D5Ac35DCAd8d05Db53EbA29978c2; address public guardian; address public converter; address public punkProxy; uint256 public baseFees; bool public openForTrades; bool public openForFreeTrades; MarketRegistry public marketRegistry; AffiliateDetails[] public affiliates; SponsoredMarket[] public sponsoredMarkets; modifier isOpenForTrades() { require(openForTrades, "trades not allowed"); _; } modifier isOpenForFreeTrades() { require(openForFreeTrades, "free trades not allowed"); _; } constructor(address _marketRegistry, address _converter, address _guardian) { marketRegistry = MarketRegistry(_marketRegistry); converter = _converter; guardian = _guardian; baseFees = 0; openForTrades = true; openForFreeTrades = true; affiliates.push(AffiliateDetails(GOV, true)); } function setUp() external onlyOwner { // Create CryptoPunk Proxy IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).registerProxy(); punkProxy = IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).proxyInfo(address(this)); // approve wrapped mooncats rescue to Acclimated​MoonCats contract IERC721(0x7C40c393DC0f283F318791d746d894DdD3693572).setApprovalForAll(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69, true); } // @audit This function is used to approve specific tokens to specific market contracts with high volume. // This is done in very rare cases for the gas optimization purposes. function setOneTimeApproval(IERC20 token, address operator, uint256 amount) external onlyOwner { token.approve(operator, amount); } function updateGuardian(address _guardian) external onlyOwner { guardian = _guardian; } function addAffiliate(address _affiliate) external onlyOwner { affiliates.push(AffiliateDetails(_affiliate, true)); } function updateAffiliate(uint256 _affiliateIndex, address _affiliate, bool _IsActive) external onlyOwner { affiliates[_affiliateIndex] = AffiliateDetails(_affiliate, _IsActive); } function addSponsoredMarket(uint256 _marketId) external onlyOwner { sponsoredMarkets.push(SponsoredMarket(_marketId, true)); } function updateSponsoredMarket(uint256 _marketIndex, uint256 _marketId, bool _isActive) external onlyOwner { sponsoredMarkets[_marketIndex] = SponsoredMarket(_marketId, _isActive); } function setBaseFees(uint256 _baseFees) external onlyOwner { baseFees = _baseFees; } function setOpenForTrades(bool _openForTrades) external onlyOwner { openForTrades = _openForTrades; } function setOpenForFreeTrades(bool _openForFreeTrades) external onlyOwner { openForFreeTrades = _openForFreeTrades; } // @audit we will setup a system that will monitor the contract for any leftover // assets. In case any asset is leftover, the system should be able to trigger this // function to close all the trades until the leftover assets are rescued. function closeAllTrades() external { require(_msgSender() == guardian); openForTrades = false; openForFreeTrades = false; } function setConverter(address _converter) external onlyOwner { converter = _converter; } function setMarketRegistry(MarketRegistry _marketRegistry) external onlyOwner { marketRegistry = _marketRegistry; } function _transferEth(address _to, uint256 _amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), _to, _amount, 0, 0, 0, 0) } require(callStatus, "_transferEth: Eth transfer failed"); } function _collectFee(uint256[2] memory feeDetails) internal { require(feeDetails[1] >= baseFees, "Insufficient fee"); if (feeDetails[1] > 0) { AffiliateDetails memory affiliateDetails = affiliates[feeDetails[0]]; affiliateDetails.isActive ? _transferEth(affiliateDetails.affiliate, feeDetails[1]) : _transferEth(GOV, feeDetails[1]); } } function _checkCallResult(bool _success) internal pure { if (!_success) { // Copy revert reason from call assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } function _transferFromHelper( ERC20Details memory erc20Details, SpecialTransferHelper.ERC721Details[] memory erc721Details, ERC1155Details[] memory erc1155Details ) internal { // transfer ERC20 tokens from the sender to this contract for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) { erc20Details.tokenAddrs[i].call(abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), erc20Details.amounts[i])); } // transfer ERC721 tokens from the sender to this contract for (uint256 i = 0; i < erc721Details.length; i++) { // accept CryptoPunks if (erc721Details[i].tokenAddr == 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB) { _acceptCryptoPunk(erc721Details[i]); } // accept Mooncat else if (erc721Details[i].tokenAddr == 0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6) { _acceptMoonCat(erc721Details[i]); } // default else { for (uint256 j = 0; j < erc721Details[i].ids.length; j++) { IERC721(erc721Details[i].tokenAddr).transferFrom( _msgSender(), address(this), erc721Details[i].ids[j] ); } } } // transfer ERC1155 tokens from the sender to this contract for (uint256 i = 0; i < erc1155Details.length; i++) { IERC1155(erc1155Details[i].tokenAddr).safeBatchTransferFrom( _msgSender(), address(this), erc1155Details[i].ids, erc1155Details[i].amounts, "" ); } } function _conversionHelper( ConverstionDetails[] memory _converstionDetails ) internal { for (uint256 i = 0; i < _converstionDetails.length; i++) { // convert to desired asset (bool success, ) = converter.delegatecall(_converstionDetails[i].conversionData); // check if the call passed successfully _checkCallResult(success); } } function _trade( MarketRegistry.TradeDetails[] memory _tradeDetails ) internal { for (uint256 i = 0; i < _tradeDetails.length; i++) { // get market details (address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId); // market should be active require(_isActive, "_trade: InActive Market"); // execute trade if (_proxy == 0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b) { _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData); } else { (bool success, ) = _isLib ? _proxy.delegatecall(_tradeDetails[i].tradeData) : _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData); // check if the call passed successfully _checkCallResult(success); } } } // function _tradeSponsored( // MarketRegistry.TradeDetails[] memory _tradeDetails, // uint256 sponsoredMarketId // ) internal returns (bool isSponsored) { // for (uint256 i = 0; i < _tradeDetails.length; i++) { // // check if the trade is for the sponsored market // if (_tradeDetails[i].marketId == sponsoredMarketId) { // isSponsored = true; // } // // get market details // (address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId); // // market should be active // require(_isActive, "_trade: InActive Market"); // // execute trade // if (_proxy == 0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b) { // _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData); // } else { // (bool success, ) = _isLib // ? _proxy.delegatecall(_tradeDetails[i].tradeData) // : _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData); // // check if the call passed successfully // _checkCallResult(success); // } // } // } function _returnDust(address[] memory _tokens) internal { // return remaining ETH (if any) assembly { if gt(selfbalance(), 0) { let callStatus := call( gas(), caller(), selfbalance(), 0, 0, 0, 0 ) } } // return remaining tokens (if any) for (uint256 i = 0; i < _tokens.length; i++) { if (IERC20(_tokens[i]).balanceOf(address(this)) > 0) { _tokens[i].call(abi.encodeWithSelector(0xa9059cbb, msg.sender, IERC20(_tokens[i]).balanceOf(address(this)))); } } } function batchBuyFromOpenSea( OpenseaTrades[] memory openseaTrades ) payable external nonReentrant { // execute trades for (uint256 i = 0; i < openseaTrades.length; i++) { // execute trade address(0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b).call{value:openseaTrades[i].value}(openseaTrades[i].tradeData); } // return remaining ETH (if any) assembly { if gt(selfbalance(), 0) { let callStatus := call( gas(), caller(), selfbalance(), 0, 0, 0, 0 ) } } } function batchBuyWithETH( MarketRegistry.TradeDetails[] memory tradeDetails ) payable external nonReentrant { // execute trades _trade(tradeDetails); // return remaining ETH (if any) assembly { if gt(selfbalance(), 0) { let callStatus := call( gas(), caller(), selfbalance(), 0, 0, 0, 0 ) } } } function batchBuyWithERC20s( ERC20Details memory erc20Details, MarketRegistry.TradeDetails[] memory tradeDetails, ConverstionDetails[] memory converstionDetails, address[] memory dustTokens ) payable external nonReentrant { // transfer ERC20 tokens from the sender to this contract for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) { erc20Details.tokenAddrs[i].call(abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), erc20Details.amounts[i])); } // Convert any assets if needed _conversionHelper(converstionDetails); // execute trades _trade(tradeDetails); // return dust tokens (if any) _returnDust(dustTokens); } // swaps any combination of ERC-20/721/1155 // User needs to approve assets before invoking swap // WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!! function multiAssetSwap( ERC20Details memory erc20Details, SpecialTransferHelper.ERC721Details[] memory erc721Details, ERC1155Details[] memory erc1155Details, ConverstionDetails[] memory converstionDetails, MarketRegistry.TradeDetails[] memory tradeDetails, address[] memory dustTokens, uint256[2] memory feeDetails // [affiliateIndex, ETH fee in Wei] ) payable external isOpenForTrades nonReentrant { // collect fees _collectFee(feeDetails); // transfer all tokens _transferFromHelper( erc20Details, erc721Details, erc1155Details ); // Convert any assets if needed _conversionHelper(converstionDetails); // execute trades _trade(tradeDetails); // return dust tokens (if any) _returnDust(dustTokens); } // Utility function that is used for free swaps for sponsored markets // WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!! // function multiAssetSwapWithoutFee( // ERC20Details memory erc20Details, // SpecialTransferHelper.ERC721Details[] memory erc721Details, // ERC1155Details[] memory erc1155Details, // ConverstionDetails[] memory converstionDetails, // MarketRegistry.TradeDetails[] memory tradeDetails, // address[] memory dustTokens, // uint256 sponsoredMarketIndex // ) payable external isOpenForFreeTrades nonReentrant { // // fetch the marketId of the sponsored market // SponsoredMarket memory sponsoredMarket = sponsoredMarkets[sponsoredMarketIndex]; // // check if the market is active // require(sponsoredMarket.isActive, "multiAssetSwapWithoutFee: InActive sponsored market"); // // // transfer all tokens // _transferFromHelper( // erc20Details, // erc721Details, // erc1155Details // ); // // // Convert any assets if needed // _conversionHelper(converstionDetails); // // // execute trades // bool isSponsored = _tradeSponsored(tradeDetails, sponsoredMarket.marketId); // // // check if the trades include the sponsored market // require(isSponsored, "multiAssetSwapWithoutFee: trades do not include sponsored market"); // // // return dust tokens (if any) // _returnDust(dustTokens); // } function onERC1155Received( address, address, uint256, uint256, bytes calldata ) public virtual returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) public virtual returns (bytes4) { return this.onERC1155BatchReceived.selector; } function onERC721Received( address, address, uint256, bytes calldata ) external virtual returns (bytes4) { return 0x150b7a02; } // Used by ERC721BasicToken.sol function onERC721Received( address, uint256, bytes calldata ) external virtual returns (bytes4) { return 0xf0b9e5ba; } function supportsInterface(bytes4 interfaceId) external virtual view returns (bool) { return interfaceId == this.supportsInterface.selector; } receive() external payable {} // Emergency function: In case any ETH get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueETH(address recipient) onlyOwner external { _transferEth(recipient, address(this).balance); } // Emergency function: In case any ERC20 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC20(address asset, address recipient) onlyOwner external { asset.call(abi.encodeWithSelector(0xa9059cbb, recipient, IERC20(asset).balanceOf(address(this)))); } // Emergency function: In case any ERC721 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC721(address asset, uint256[] calldata ids, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC721(asset).transferFrom(address(this), recipient, ids[i]); } } // Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], ""); } } } // 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.11; /// @notice Gas optimized reentrancy protection for smart contracts. /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol) abstract contract ReentrancyGuard { uint256 private reentrancyStatus = 1; modifier nonReentrant() { require(reentrancyStatus == 1, "REENTRANCY"); reentrancyStatus = 2; _; reentrancyStatus = 1; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; contract MarketRegistry is Ownable { struct TradeDetails { uint256 marketId; uint256 value; bytes tradeData; } struct Market { address proxy; bool isLib; bool isActive; } Market[] public markets; constructor(address[] memory proxies, bool[] memory isLibs) { for (uint256 i = 0; i < proxies.length; i++) { markets.push(Market(proxies[i], isLibs[i], true)); } } function addMarket(address proxy, bool isLib) external onlyOwner { markets.push(Market(proxy, isLib, true)); } function setMarketStatus(uint256 marketId, bool newStatus) external onlyOwner { Market storage market = markets[marketId]; market.isActive = newStatus; } function setMarketProxy(uint256 marketId, address newProxy, bool isLib) external onlyOwner { Market storage market = markets[marketId]; market.proxy = newProxy; market.isLib = isLib; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/Context.sol"; import "../../interfaces/punks/ICryptoPunks.sol"; import "../../interfaces/punks/IWrappedPunk.sol"; import "../../interfaces/mooncats/IMoonCatsRescue.sol"; contract SpecialTransferHelper is Context { struct ERC721Details { address tokenAddr; address[] to; uint256[] ids; } function _uintToBytes5(uint256 id) internal pure returns (bytes5 slicedDataBytes5) { bytes memory _bytes = new bytes(32); assembly { mstore(add(_bytes, 32), id) } bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(5, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, 5) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), 27) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, 5) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } assembly { slicedDataBytes5 := mload(add(tempBytes, 32)) } } function _acceptMoonCat(ERC721Details memory erc721Details) internal { for (uint256 i = 0; i < erc721Details.ids.length; i++) { bytes5 catId = _uintToBytes5(erc721Details.ids[i]); address owner = IMoonCatsRescue(erc721Details.tokenAddr).catOwners(catId); require(owner == _msgSender(), "_acceptMoonCat: invalid mooncat owner"); IMoonCatsRescue(erc721Details.tokenAddr).acceptAdoptionOffer(catId); } } function _transferMoonCat(ERC721Details memory erc721Details) internal { for (uint256 i = 0; i < erc721Details.ids.length; i++) { IMoonCatsRescue(erc721Details.tokenAddr).giveCat(_uintToBytes5(erc721Details.ids[i]), erc721Details.to[i]); } } function _acceptCryptoPunk(ERC721Details memory erc721Details) internal { for (uint256 i = 0; i < erc721Details.ids.length; i++) { address owner = ICryptoPunks(erc721Details.tokenAddr).punkIndexToAddress(erc721Details.ids[i]); require(owner == _msgSender(), "_acceptCryptoPunk: invalid punk owner"); ICryptoPunks(erc721Details.tokenAddr).buyPunk(erc721Details.ids[i]); } } function _transferCryptoPunk(ERC721Details memory erc721Details) internal { for (uint256 i = 0; i < erc721Details.ids.length; i++) { ICryptoPunks(erc721Details.tokenAddr).transferPunk(erc721Details.to[i], erc721Details.ids[i]); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IERC20 { /** * @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 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 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 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); } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IERC721 { /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) external; function setApprovalForAll(address operator, bool approved) external; function approve(address to, uint256 tokenId) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function balanceOf(address _owner) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IERC1155 { function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external; function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; function balanceOf(address _owner, uint256 _id) 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.11; interface ICryptoPunks { function punkIndexToAddress(uint index) external view returns(address owner); function offerPunkForSaleToAddress(uint punkIndex, uint minSalePriceInWei, address toAddress) external; function buyPunk(uint punkIndex) external payable; function transferPunk(address to, uint punkIndex) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IWrappedPunk { /** * @dev Mints a wrapped punk */ function mint(uint256 punkIndex) external; /** * @dev Burns a specific wrapped punk */ function burn(uint256 punkIndex) external; /** * @dev Registers proxy */ function registerProxy() external; /** * @dev Gets proxy address */ function proxyInfo(address user) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IMoonCatsRescue { function acceptAdoptionOffer(bytes5 catId) payable external; function makeAdoptionOfferToAddress(bytes5 catId, uint price, address to) external; function giveCat(bytes5 catId, address to) external; function catOwners(bytes5 catId) external view returns(address); function rescueOrder(uint256 rescueIndex) external view returns(bytes5 catId); }
get market details market should be active execute trade check if the call passed successfully
function _trade( MarketRegistry.TradeDetails[] memory _tradeDetails ) internal { for (uint256 i = 0; i < _tradeDetails.length; i++) { (address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId); require(_isActive, "_trade: InActive Market"); if (_proxy == 0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b) { (bool success, ) = _isLib ? _proxy.delegatecall(_tradeDetails[i].tradeData) _checkCallResult(success); } } }
89,118